/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Album.js
 * @path:   js-src/album/
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */

var GLOBAL = GLOBAL || {};
GLOBAL.user = {
    area: "sh"
};
GLOBAL.currentDate = Com.date.getCurrentDate();



define(
    '../ancestor/Ancestor',['require','exports','module'],function(require, exports, module) {


        ///import js-src/lib/
        ///import js-src/com/

        window.Ancestor = window.Ancestor || {
            version: '1.0'
        };


    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-12
 */
define(
    '../ancestor/Ancestor.Dao',['require','exports','module'],function(require, exports, module) {

        Ancestor.Dao = (function() {
            var config = Ancestor.Config;

            var ajax = function(options, authPath) {
                if (authPath)
                    $.ajax($.extend(options, {
                        beforeSend: function(request) {
                            var authBase = Ancestor.Util.getAuth(authPath);
                            request.setRequestHeader('Sign', authBase.sign);
                            request.setRequestHeader("Time", authBase.clientTime);
                            request.setRequestHeader("From", authBase.from);
                            request.setRequestHeader("UserName", (auth.baseInfo.authInfo==null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                        }
                    }));
                else
                    $.ajax(options);
            };

            // 获取配频道配置数据
            var getType = function(data, callback) {
                var options = {
                    url: config.CONFIGS_API.url,
                    dataType: 'json',
                    data: data,
                    method: 'get',

                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/configs");

            };

            var getSuggestData = function(url, data, callback) {

                var request = {};
                request.url = url;
                request.type = 'get';

                if (data.needCookie)
                    request.needCookie = true;

                request.params = data;

                data = {
                    request: JSON.stringify(request)
                };

                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, '/redirect');
            };

            var getQipuDataById = function(item, callback) {
                var url = Ancestor.Config.QIPU_URL.replace("${QIPUID}", item.qipuId);

                var request = {};
                request.url = url;
                request.type = 'get';

                var data = {
                    request: JSON.stringify(request)
                };

                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    method: 'post',
                    data: data,
                    success: function(data) {
                        callback.call(this, data, item);
                    },
                    error: function(data) {
                        callback.call(this, data, item);
                    }
                };

                ajax(options, '/redirect');
            };

            // 获取分类
            var getuniversalCodeData = function(url, data, callback) {

                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, url.split('api')[1]);
            };

            // XMLHttp Request
            var _getXHR = function() {
                return new XMLHttpRequest() || new ActiveXObject('Msxml2.XMLHTTP') || new ActiveXObject('Microsoft.XMLHTTP');
            };

            var qichuanUploadFile = function(data, handler) {
                var self = this;
                var xhr = _getXHR();
                var precent = 0;
                xhr.open('POST', data.url, true);
                // xhr.setRequestHeader('Content-Type', 'multipart/form-data');
                for (var key in data.headers) {
                    xhr.setRequestHeader(key, data.headers[key]);
                }

                xhr.upload.onprogress = function(e) {
                    var data = xhr.responseText ? JSON.parse(xhr.responseText) : null;
                    if (e.lengthComputable) {
                        precent = (e.loaded / e.total) * 100;
                        if (handler.onProgress) {
                            handler.onProgress.apply(self, [precent, data]);
                        }
                    }
                };

                xhr.onreadystatechange = function() {
                    var data = xhr.responseText ? JSON.parse(xhr.responseText) : null;
                    if (xhr.readyState == 4) {
                        var stat = xhr.status;
                        if ((stat >= 200 && stat < 300) || stat == 304 || stat == 1223 || stat === 0) {
                            if (handler.onFinish) {
                                handler.onFinish.call(self, data);
                            }
                        } else {
                            if (handler.onFail) {
                                handler.onFail.call(self, data);
                            }
                        }
                    }
                };

                var formData = new FormData();
                formData.append('businessType', data.headers['businessType']);
                formData.append('fileid', data.headers['file_id']);
                formData.append('imagefile', data.file);

                // xhr.send(data.file || null);
                xhr.send(formData);


                return xhr;
            };


            var qichuanRequestFile = function(options, callback) {
                options = options || {};
                var headers = options.headers || {};

                var options = {
                    url: options.url + '?t=' + new Date().getTime(),
                    // url: options.url,
                    dataType: 'json',
                    // data: data,
                    headers: headers,
                    method: 'get',
                    success: function(data) {
                        if (data && data.code == 'A00000') {
                            callback.call(this, data);
                        } else {
                            console.log('get access fail.');
                            callback.call(this, data);
                        }
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, false);

            };

            var platSettings = function(options, callback) {
                var options = {
                    url: '/api/channel/getPlatSettings',
                    dataType: 'json',
                    data: options,
                    method: 'post',

                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/channel/getPlatSettings");
            };

            var redirectRequest = function(options, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: options,
                    method: 'post',
                    beforeSend: function(request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/redirect");
            };

            return {
                getType: getType,
                qichuanRequestFile: qichuanRequestFile,
                qichuanUploadFile: qichuanUploadFile,
                getSuggestData: getSuggestData,
                platSettings: platSettings,
                getuniversalCodeData: getuniversalCodeData,
                getQipuDataById: getQipuDataById,
                redirectRequest: redirectRequest,
                ajax: ajax
            };
        })();
    }
);
/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 * 
 * @file: Ancestor.Base.js
 * @path: js-src/Ancestor/
 * @desc: Ancestor模块下基础业对象类
 * @author: lichuning@qiyi.com
 * @date: 2013-04-10
 */
///import js-src/lib/
///import js-src/com/

define('../ancestor/Ancestor.Grid',['require','exports','module'],function(require, exports, module) {

    Ancestor.Grid = function(options) {};
    /**
     * 每个Action都设置一个初始化方法 用于初始化Ancestor 原型对象，默认不重复初始化
     *
     * @param {Boolean}
     *            force 是否强制初始化
     *
     */
    Ancestor.Grid.prototype = $.extend(true, {}, Com.Grid, {
        filterDataWhenBatchOper: function(data, filter) {
            filter = filter || function(item) {
                return !item.del;
            };

            data = $.grep(data, function(item) {

                return filter(item);
            });

            return data;
        },
        /**
         * 素材库查询方法
         * @param params 查询参数，采用jquery formSerialize
         * @param callback
         */
        query: function(callback) {

            var self = this;
            var $grid = self.$grid;

            var params = this.getParam();

            $grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid', [{
                page: 1
            }]);

        },
        getParam: function() {

            var self = this;
            var $container = self.options.$container;
            var $grid = self.$grid;
            Com.Grid.overridePostData($grid);
            var params = {};
            var $elements = $.makeArray($container.find('form.query').prop('elements'));

            $.each($elements, function() {
                if (this.name) {
                    var key = $(this).attr('data-key');
                    if (key) {
                        params[this.name] = $(this).attr(key) || '';
                    } else {
                        params[this.name] = $(this).val();
                    }
                }
            });

            return params;
        },

        echoQuery: function() {
            var self = this;
            var $container = self.options.$container;

            this.query();

        },

        getGrid: function() {
            return this.$grid;
        },

        run: function(options, callback) {


            this.bindEvent();
            this.echoQuery();
            this.initGrid.call(this, options, callback);

        },

        setType: function(type) {
            this.options.type = type;
        },

        getType: function() {
            return this.options.type;
        },

        getGridConfig: function(table, tableColModel) {
            var self = this;
            var tableConfig = $.extend(true, {}, table || self.config.TABLE);
            var colModel = tableConfig.colModel;
            var newColModel = [];
            var colModelConfig = tableColModel || self.config.TABLE_COLMODEL_CONFIG;

            $.each(colModel, function(i, model) {
                newColModel.push(colModelConfig[model]);
            });
            tableConfig.colModel = newColModel;
            return tableConfig;
        },

        initGrid: function(options, callback) {
            var self = this;

            var gridConfig = self.getGridConfig();

            var $gridContainer = self.options.$container;

            var type = self.getType();
            var $pager = $gridContainer.find('div.pager');
            var $grid = $gridContainer.find('table.grid');
            var params = self.getParam();
            options = $.extend(true, {
                pager: $pager,
                mtype: 'post',

                postData: $.extend(true, {
                    type: type

                }, params),

                sortname: 'createTime',
                sortorder: 'desc',


                multiselect: true,

                multiselectWidth: 30

            }, gridConfig, options);

            $grid.jqGrid('scroll', {});
            $grid.jqGrid(options);

        },

        bindEvent: function() {
            var self = this;
            var $container = this.options.$container;
            var $form = $container.find('form[name="basicFrm"]');

            /*
             * 绑定时间
             *
             */
            //$.datepicker.setDefaults( $.datepicker.regional[ "" ] );

            $container.find("#StartTime").datetimepicker({
                onClose: function(selectedDate) {
                    $("#EndTime").datepicker("option", "minDate", selectedDate);
                }

            });

            $container.find("#EndTime").datetimepicker({
                onClose: function(selectedDate) {
                    $("#StartTime").datepicker("option", "maxDate", selectedDate);
                }
            });

            $form.find('button[type="reset"]').click(function() {
                self.resetQueryForm();
            });
        },

        resetQueryForm: function() {
            var self = this;
            var $container = this.options.$container;
            var $form = $container.find('form[name="basicFrm"]');
            // 从suggest获得的数据都需要清空
            $form.find('input[data-key]').removeAttr('data-id');
        },

        reload: function(params) {
            var type = this.getType();
            params = $.extend(true, {
                type: type
            }, params);
            this.$grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid');
        },

        // 基本数据请求队列
        ajaxBasicRequestQueue: (function() {
            var Queue = [];

            var pushData = function(obj) {
                Queue.push(obj);
            };
            var getQueueLen = function() {
                return Queue.length;
            };
            var getQueueData = function() {
                return Queue;
            };
            var clearQueueData = function() {
                Queue = [];
            };

            return {
                pushData: pushData,
                getQueueLen: getQueueLen,
                getQueueData: getQueueData,
                clearQueueData: clearQueueData
            };

        })(),

        ajaxBasicRequestLen: -1,
        intverId: null,

        // 处理请求队列
        ajaxBasicRequestManage: (function() {

            var self = null,
                fct = null,
                tryNumbers = 10000; //尝试10000次

            var init = function(obj, func) {
                self = obj;
                fct = func;
                start();
            };

            var start = function() {
                var len = self.ajaxBasicRequestQueue.getQueueLen();
                if (len === 0) return;

                if (self.ajaxBasicRequestLen == len || tryNumbers == 1) {
                    clearInterval(self.intverId);
                    fct(self);
                    self.ajaxBasicRequestQueue.clearQueueData();
                } else if (self.ajaxBasicRequestLen != -1) {
                    return;
                } else {
                    var queue = self.ajaxBasicRequestQueue.getQueueData();
                    self.ajaxBasicRequestLen = 0;

                    $.each(queue, function(i, item) {
                        item.func(function() {
                            self.ajaxBasicRequestLen++;
                        });
                    });
                    self.intverId = setInterval(start, 10);
                }
                tryNumbers--;
            };
            return {
                init: init
            };
        })(),
    });

});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define('../ancestor/Ancestor.Config',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/
    Ancestor.Config = (function() {
        var REQUEST_FAIL = "接口响应超时,请稍后再试！";
        var QICHUAN = {

            //image_requestURL: 'http://upload.iqiyi.com/request_image_upload',
            image_requestURL_test: 'http://upload.iqiyi.com/request_image_upload',

            image_uploadURL: 'http://upload.iqiyi.com/image_upload',
            image_uploadURL_inner: 'http://upload.qiyi.domain/image_upload',
            image_uploadURL_test: 'http://upload.iqiyi.com/image_upload',

            deviceId: 'LEGO-uploader',
        };

        var EPG_AUTH = {

            From: 'frontend', // 来源
            key: '7dpHGKMy4hAh3DmC' // 密钥

        };

        var CONFIGS_API = {
            url: '/api/configs'
        };

        // 直转点 频道名称
        var CATEGORY_NAME = [];

        // 直播类型
        var LIVE_TYPE = [];

        // 频道分类
        var CHANNEL_TYPE = [];


        // 日志分类
        var LOG_TYPE = [];

        // 备播库标色提示
        var APC_WARNING = {
            NORMAL: 'black',
            RED: 'red',
            ORANGE: '#ffa800'
        };

        var PLATFORM_TYPE = null;
        var PLATFORM_REFER = null;

        // 奇谱url
        var QIPU_URL = (function() {
            var qipuUrl = auth.dev() ? 'http://qipu-test.qiyi.domain/int/entity/nocache/${QIPUID}.json' : 'http://qipu.qiyi.domain/int/entity/nocache/${QIPUID}.json';
            return qipuUrl;
        })();

        return {
            EPG_AUTH: EPG_AUTH,
            LIVE_TYPE: LIVE_TYPE,
            CHANNEL_TYPE: CHANNEL_TYPE,
            QICHUAN: QICHUAN,
            CONFIGS_API: CONFIGS_API,
            LOG_TYPE: LOG_TYPE,
            APC_WARNING: APC_WARNING,
            PLATFORM_REFER: PLATFORM_REFER,
            PLATFORM_TYPE: PLATFORM_TYPE,
            QIPU_URL: QIPU_URL,
            REQUEST_FAIL: REQUEST_FAIL,
            CATEGORY_NAME:CATEGORY_NAME
        };


    })();

});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Util.js
 * @path:   js/Ancestor/
 * @desc:
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define('../ancestor/Ancestor.Util',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/

    Ancestor.Util = (function() {

        Date.prototype.format = function (format) {
        var o = {
                  "M+" : this.getMonth() + 1, //month
                  "d+" : this.getDate(), //day
                  "h+" : this.getHours(), //hour
                  "m+" : this.getMinutes(), //minute
                  "s+" : this.getSeconds(), //second
                  "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter
                  "S" : this.getMilliseconds() //millisecond
              }

              if (/(y+)/.test(format)) {
                  format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
              }

              for (var k in o) {
                  if (new RegExp("(" + k + ")").test(format)) {
                      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                  }
              }
              return format;
          };

        // 组装 sign
        var authorization = function(options) {
            var rawSign = options.url + options.clientTime + Ancestor.Config.EPG_AUTH.key;
            return md5(rawSign);
        };

        /**
         * 设置截图编辑的整体，包括截图、幻灯片、上传三个部分
         * @param $imgcrop Object 整体的DOM结构，jQuery Object
         * @param images Array<String> 初始化用的图片URL数组
         * @param width 如果有幻灯片的话，幻灯片部分的宽度
         */
        var imageCrop = function($imgcrop) {
            // try{
            var $slideshow = $imgcrop.find('.slideshow');
            var $enableBtn = $imgcrop.find('button.button-enable');
            var $uploadBtn = $imgcrop.find('input.uploadButton');
            var $btnOnline = $imgcrop.find('button.button-online');
            var gallery, t, flag;
            // 设置下面的缩略图
            $slideshow.gallery({
                thumbnail: '.item',
                prevButton: $slideshow.find('button.left'),
                nextButton: $slideshow.find('button.right')
            });
            gallery = $slideshow.data('gallery');
            t = gallery.totalItems;
            // 设置上传图片按钮
            if ($uploadBtn.length) {
                $uploadBtn.uploadDialog({
                    gallery: $imgcrop.find('.gallery'),
                    onStart: function() {
                        gallery.update();
                        gallery.scrollTo(t);
                    }
                });
            }
            $(window).resize(function(e) {
                gallery.update();
            });
            // 设置截图控件
            $imgcrop.imageCrop({
                'gallery': '.gallery',
                'cropimg': '.cropimg',
                'results': '.results'
            });
            // 设置激活按钮
            if ($('#_entityId').val()) {
                $enableBtn.click(function(e) {
                    $imgcrop.data('imageCrop').enable();
                    $enableBtn.attr('disabled', true);
                    gallery.scrollTo(0);
                });
                $imgcrop.data('imageCrop').disable();
                $enableBtn.attr('disabled', false);
            } else {
                $imgcrop.data('imageCrop').enable();
                $enableBtn.attr('disabled', true);
                $enableBtn.hide();
            }
          $imgcrop.find('.header input').enable();
            if ('1' === $('#ThriftVideoMakeStatus').val() && '1' != $('#entityType').val()) {
                $btnOnline.show();
            } else {
                $btnOnline.hide();
            }
            // 设置在线视频截图
            /*
            if ($btnOnline.length) {
                $('#AlbumEditVideoShot').videoShot({
                    onFinish: function(area, images) {
                        var data = [];
                        $.each(images, function(index, image) {
                            data.push({
                                shot: true,
                                url: image,
                                area: area
                            });
                        });
                        $imgcrop.data('imageCrop').addImages(data);
                    }
                });
                $btnOnline.click(function(e) {
                    $('#AlbumEditVideoShot').dialog('open');
                });
            }
            */

            // }catch(e){}
        };


        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function(textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function() {
                    t(this);
                },
                propertychange: function() {
                    t(this);
                },
                keyup: function() {
                    t(this);
                }
            }).trigger('keyup');
            $des.keyup();
        };

        getParam = function($obj) {

            var $container = $obj;
            var params = {};
            var $form = $obj;

            var $elements = $.makeArray($form.prop('elements')).filter(function() {
                return true; //this.name; 
            });

            var name;
            var key;
            $.each($elements, function() {
                name = this.name;
                if (name) {

                    if (this.type == 'radio') {
                        params[name] = $('input[name="' + name + '"]:checked').val() || '';
                    } else
                        params[name] = $.trim($(this).val()) || '';

                }

            });

            params['logoUrl'] = imageObject($obj);
            return params;

        };

        imageObjectEcho = function($form, value) {

            if (value) {
                value = ('object' == typeof(value) ? value : JSON.parse(value || '[]'));
            } else {
                value = null;
            }
            if (!value) {
                return;
            }

            var imageObject = value;
            var filterType = function(type) {
                var imageData = null;
                $.each(imageObject, function(index, value) {
                    if (value.useType == type) {
                        imageData = value;
                    }
                });
                return imageData;
            };
            var spathToURL = function(images, spath) {
                var url = null;
                $.each(images, function(index, image) {
                    if (spath === image.spath) {
                        url = image.url;
                    }
                });
                return url;
            };

            $form.find('div.module-container-screen-crop').each(function(index, element) {
                var $croparea = $(this);
                var imageCrop = $croparea.data('imageCrop');
                var useType = 699; //parseInt($croparea.find('input[name="useType"]').val(), 10);
                var imageData = filterType(useType);
                var imageRank = imageData && imageData.contentRank ? imageData.contentRank : 0;
                var images = [],
                    results = {};

                if (!imageData) {
                    return;
                }

                // 回显图片分级的选项
                $croparea.find('input[name^="contentRank"]').each(function(key, value) {
                    value.checked = (imageRank == value.value);
                });

                $.each(imageData.materials, function(index, material) {
                    //images.push(material.bigThumbUrl || material.location);
                    // todo: type
                    images.push({
                        spath: material.location,
                        url: material.url,
                        data: material
                    });
                });
                $.each(imageData.images, function(index, image) {
                    var scale = image.editInfo.scale;
                    var cutPosition = image.editInfo.cutPosition.split(',');
                    var width = scale.substring(0, scale.indexOf(':'));
                    var height = scale.substring(scale.indexOf(':') + 1);
                    results[width + '-' + height] = {
                        spath: image.materialLocation,
                        imgsrc: spathToURL(images, image.materialLocation),
                        w: width,
                        h: height,
                        x1: parseInt(cutPosition[0], 10),
                        y1: parseInt(cutPosition[1], 10),
                        x2: parseInt(cutPosition[0], 10) + parseInt(cutPosition[3], 10),
                        y2: parseInt(cutPosition[1], 10) + parseInt(cutPosition[2], 10),
                        data: image
                    };
                });
                imageCrop.addImages(images, function() {
                    imageCrop.setValue(results);
                });
            });
        };


        imageObject = function($form) {
            var imageObject = [];
            $form.find('div.module-container-screen-crop').each(function(index, element) {
                var $croparea = $(this);
                var useType = parseInt($croparea.find('input[name="useType"]').val(), 10);
                var contentRank = parseInt($croparea.find('input[name^="contentRank"]:checked').val(), 10) || 0; // 默认图片分级是无分级，0
                var testFlag = 0;
                var imageData = {
                    materials: [],
                    images: [],
                    useType: 699, //useType,
                    contentRank: contentRank // 图片分级的需求，默认是无分级
                };
                $croparea.find('.gallery img').each(function(index, material) {
                    var $material = $(material);
                    if (true === $material.data('loading')) {
                        return;
                    }
                    var tmp = $material.data('data') || {
                        // @todo
                        'location': $material.data('spath') || '',
                        'url': $material.attr('src'),
                        'fromType': $material.data('type'),
                        'area': 'bj', //$material.data('area'),
                        'width': $material.data('width'),
                        'height': $material.data('height')
                    };
                    imageData.materials.push(tmp);
                    testFlag++;
                });
                $.each($croparea.data('imageCrop').getValue(), function(index, value) {
                    var tmp = $.extend(value.data, {
                        materialLocation: value.spath || value.imgsrc || '',
                        editInfo: {
                            cutPosition: [value.x1, value.y1, value.y2 - value.y1, value.x2 - value.x1].join(','),
                            scale: value.w + ':' + value.h
                        }
                    });
                    imageData.images.push(tmp);
                    //testFlag |= Math.pow(2, value.index);
                });
                var type = $form.find('input[name="entityType"]').val();
                if (('0' == type && (parseInt($form.find('input[name="video.id"]').val(), 10) > 0))
                    // 如果是节目且专辑id禁用表示编目修改
                    || ('1' === type && (parseInt($form.find('input[name="album.id"]').val(), 10) > 0))
                    // 如果是专辑有#_entityId表示修改
                    || ($form.find('input[name=pilosityType]').val() && $form.find('input[name=baseId]').val())
                    // 如果是一文多发有pilosity且有baseId表示修改
                ) {
                    // 节目，专辑, 一文多发，兼容旧的，修改的时候不验证截图
                    testFlag = 99;
                }
                $croparea.find('input[name="_image_crop_' + useType + '"]').val(testFlag);
                imageObject.push(imageData);
            });
            return JSON.stringify(imageObject);
        };


        getUrlId = function(name) {

            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
                return r[2];
            return null;
        };

        fillFieldNameWhenChangeSelect = function($form, elClazzName, fieldClazzName) {
            $form.find('.' + elClazzName).on('change', function() {
                var value = $(this).val();
                var $input = $(this).closest('.control-group').find('.' + fieldClazzName);
                $input.attr('name', value);
            });
        };


        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function(textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function() {
                    t(this);
                },
                propertychange: function() {
                    t(this);
                },
                keyup: function() {
                    t(this);
                }
            });
            $des.keyup();
        };

        var getUploadFiles = function(options, isNew) {
            if (isNew && isNew === true) {
                return new Ancestor.Upload(options);
            }
            if (!uploadFiles) {
                uploadFiles = new Ancestor.Upload(options);
            } else {
                uploadFiles.update(options);
            }
            return uploadFiles;
        };

        var isNormal = function(user) {

            return true;
        };



        // 打开对话框
        var openDlg = function(obj, title, width, height) {

            height = height || 'auto';
            var $container = obj;

            $container.dialog({
                title: title,
                appendTo: null,
                modal: true,
                width: width,
                height: height,
                position: ['top', 'top+20'],

                open: function() {
                    $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                },
                close: function() {

                }
            });
        };

        var highlight = function(data, key, term) {
            data.forEach(function(item, i) {
                key = key || 'label';
                var label = item[key];
                if (!label || !term) {
                    return;
                }
                item[key] = (item[key] + '').replace(new RegExp('(' + term + ')', 'i'), '<b>$1</b>');
                // 高亮未输入部分
                // if (label.toLowerCase().indexOf(term.toLowerCase()) == 0) {
                //     item[key] = item[key].substr(0, term.length)
                //                   + '<b>'
                //                   + item[key].substr(term.length) + '</b>';
                // }
            });
        };

        var updateParamsBySettings = function(params, entity) {
            if (!params) {
                params = {};
            }

            if (entity.checkPublishType == 1) {
                params["filter_EQI_pagePublishStatus"] = 1;
            }
            if (entity.checkCopyRightType == 1) {
                params["filter_GTI_copyrightOwnerId"] = 0;
            }
            if (entity.checkBossType == 0) {
                params["filter_INI_isPurchase"] = "0,-100";
            } else if (entity.checkBossType == 1) {
                params["filter_INI_isPurchase"] = "1,2";
            }
            var platformTypeResponse = Ancestor.Config.PLATFORM_TYPE;
            $.each(platformTypeResponse, function(i, element) {
                //   params["region_" + element.val] = 0;
                if (entity.regionLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["region_" + element.val] = 1;
                }
            });
            var platformReferResponse = Ancestor.Config.PLATFORM_REFER;
            $.each(platformReferResponse, function(i, element) {
                //   params["filter_EQI_" + element.val] = 0;
                if (entity.onlineLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["filter_EQI_" + element.val] = 1;
                }

            });
            console.log(" params:" + JSON.stringify(params));

            return params;
        };

        var createSuggest = function(el, options) {
            options = $.extend(true, {
                // 是否自动选择地一条
                autoFocus: true,
                // 选中input时请求
                focusSearch: false,
                sortBy: false,
                // 是否校验结果
                validate: false,
                // 多条时是否验证必有数据
                multipleValid: false,
                // 是否高亮
                highlight: true,
                // 是否onblur时清空无效结果
                clearInvalid: true,
                noResult: '对不起，没有这个结果',
                valueKey: 'id',
                parseValue: function() {
                    var val = this.element.val();
                    var ret = [];
                    if (val) {
                        var items = val.split(';');
                        $.each(items, function(i, item) {
                            item = item.split(',');
                            ret.push({
                                value: item[1],
                                id: item[0],
                                label: item[1]
                            });
                        });
                    }
                    this._value('');
                    return ret;
                },
                create: function(event, ui) {
                    $(this).autocomplete('init');

                    if (options.focusSearch) {
                        $(el).on('focus', function() {
                            if ($.trim(this.value) !== '') {
                                $(this).autocomplete('search');
                            }
                        });
                    }
                },
                otherParam: $.extend({}, options.params),
                source: function(request, response) {
                    var self = this;
                    var term = $.trim(request.term);
                    var result = [];
                    if (!term) {
                        return null;
                    }
                    self.getResultData = function() {
                        return result;
                    };
                    var options = this.options;
                    var dataProcess = options.process || process;
                    var param = {};
                    if (!options.ignoreWord) {
                        //传递 word  term
                        param = {
                            word: term
                        };
                    }
                    param = $.extend(true, options.otherParam, param);

                    //根据dom上定义的sugg-filter过滤项增加过滤参数
                    //sugg-filter中的过滤项以逗号分隔
                    var filterStr = $(el).attr('sugg-filter');
                    if ($.trim(filterStr)) {
                        var filters = $.trim(filterStr).split(',');
                        if (filters && filters.length > 0) {
                            for (var i = 0, l = filters.length, filter; i < l; i++) {
                                filter = filters[i].split('=');
                                if (filter.length == 2) {
                                    param[filter[0]] = filter[1];
                                }
                            }
                        }
                    }

                    var url = options.url;
                    var getParam = options.getParam;
                    if (getParam) {
                        if ($.isFunction(options.getParam)) {
                            param = $.extend(true, param, getParam.call(this, term));
                        } else if ($.isPlainObject(getParam)) {
                            param = $.extend(true, param, getParam);
                        }
                    }

                    var fetchData = function() {
                        Ancestor.Dao.getSuggestData(url, param, function(json) {
                            var ret = dataProcess.call(self, json, term);

                            var runNext = function(ret) {
                                if ($.isArray(options.sortBy)) {
                                    sortBy.apply(self, [ret].concat(options.sortBy));
                                } else if ($.isFunction(options.onSortBy)) {
                                    options.onSortBy.apply(self, [ret, term]);
                                }

                                if (options.highlight) {
                                    if ($.isFunction(options.onHighlight)) {
                                        options.onHighlight.apply(self, [ret, term]);
                                    } else {
                                        highlight(ret, null, term);
                                    }
                                }
                                result = ret;
                                if ($.isFunction(options.onLoad)) {
                                    options.onLoad.apply(self, [result, term]);
                                }
                                response(result);
                            };

                            if (options.needFetchMore) {
                                options.fetchMore(ret, runNext);
                            } else {
                                runNext(ret);
                            }
                        });
                    };

                    if (options.needPreProcess) {
                        var channelId = Com.url.getParameter("id");
                        Ancestor.Dao.platSettings({
                            channelId: channelId
                        }, function(json) {
                            if (json.code === 'A00000') {
                                param = updateParamsBySettings(param, json.data);
                                fetchData();
                            }
                        });
                    } else {
                        fetchData();
                    }


                }
            }, options);

            /* ui-front ui-suggest*/
            return $(el).wrap('<span class="ui-front ui-suggest" ></span>').autocomplete(
                options).on('autocompleteresponse', function(event, ui) {
                var content = ui.content;
                $(this).autocomplete('validate', content);
            }).on('autocompleteselect', function(event, ui) {


                //////////////////suggest选择后回显设置/////////////////////
                //  ui.item.value=ui.item.name;


                return $(this).autocomplete('setValue', ui.item);

            }).on('autocompletesearch', function(event, ui) {
                //支持多选
                return $(this).autocomplete('multiplesearch');
            });
        };

        var qitan = function(el, options) {

            var tpl = '<div><div class="contract-item">' +
                '<span class="contract-width80">${resourceId}</span>' +
                '<span class="contract-width250">{{html name}}</span>' +
                '<span class="contract-width80">${addDate}</span>' +
                '</div></div>';

            var title = {
                resourceId: '评论ID',
                name: '评论名称',
                addDate: '创建时间'
            };

            var getHtmlByData = function(data) {
                var htmls = [];
                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);
            createSuggest(el, $.extend(true, {

                url: 'http://api.t.iqiyi.com/qx_api/resource/get_id_by_name',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                otherParam: $.extend({
                    'page_size': 10,
                    'resource_type': $(el).data('type') || 1
                }, options.params),
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'name': term
                    };
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data.ids;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, item, {
                                label: item.name,
                                value: item.resourceId,
                                id: item.resourceId
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-qitan');
        };


        var universalCodeCreateSuggest = function(el, options) {
            options = $.extend(true, {
                // 是否自动选择地一条
                autoFocus: true,
                // 选中input时请求
                focusSearch: false,
                sortBy: false,
                // 是否校验结果
                validate: false,
                // 多条时是否验证必有数据
                multipleValid: false,
                // 是否高亮
                highlight: true,
                // 是否onblur时清空无效结果
                clearInvalid: true,
                noResult: '对不起，没有这个结果',
                valueKey: 'id',
                parseValue: function() {
                    var val = this.element.val();
                    var ret = [];
                    if (val) {
                        var items = val.split(';');
                        $.each(items, function(i, item) {
                            item = item.split(',');
                            ret.push({
                                value: item[1],
                                id: item[0],
                                label: item[1]
                            });
                        });
                    }
                    this._value('');
                    return ret;
                },
                create: function(event, ui) {
                    $(this).autocomplete('init');

                    if (options.focusSearch) {
                        $(el).on('focus', function() {
                            if ($.trim(this.value) !== '') {
                                $(this).autocomplete('search');
                            }
                        });
                    }
                },
                otherParam: $.extend({}, options.params),
                source: function(request, response) {
                    var self = this;
                    var term = $.trim(request.term);
                    var result = [];
                    if (!term) {
                        return null;
                    }
                    self.getResultData = function() {
                        return result;
                    };
                    var options = this.options;
                    var dataProcess = options.process || process;
                    var param = {};
                    if (!options.ignoreWord) {
                        //传递 word  term
                        param = {
                            word: term
                        };
                    }
                    param = $.extend(true, options.otherParam, param);

                    //根据dom上定义的sugg-filter过滤项增加过滤参数
                    //sugg-filter中的过滤项以逗号分隔
                    var filterStr = $(el).attr('sugg-filter');
                    if ($.trim(filterStr)) {
                        var filters = $.trim(filterStr).split(',');
                        if (filters && filters.length > 0) {
                            for (var i = 0, l = filters.length, filter; i < l; i++) {
                                filter = filters[i].split('=');
                                if (filter.length == 2) {
                                    param[filter[0]] = filter[1];
                                }
                            }
                        }
                    }

                    var url = options.url;
                    var getParam = options.getParam;
                    if (getParam) {
                        if ($.isFunction(options.getParam)) {
                            param = $.extend(true, param, getParam.call(this, term));
                        } else if ($.isPlainObject(getParam)) {
                            param = $.extend(true, param, getParam);
                        }
                    }
                    Ancestor.Dao.getuniversalCodeData(url, param, function(json) {
                        var ret = dataProcess.call(self, json, term);
                        if ($.isArray(options.sortBy)) {
                            sortBy.apply(self, [ret].concat(options.sortBy));
                        } else if ($.isFunction(options.onSortBy)) {
                            options.onSortBy.apply(self, [ret, term]);
                        }

                        if (options.highlight) {
                            if ($.isFunction(options.onHighlight)) {
                                options.onHighlight.apply(self, [ret, term]);
                            } else {
                                highlight(ret, null, term);
                            }
                        }
                        result = ret;
                        if ($.isFunction(options.onLoad)) {
                            options.onLoad.apply(self, [result, term]);
                        }
                        response(result);
                    });

                }
            }, options);

            /* ui-front ui-suggest*/
            return $(el).wrap('<span class="ui-front ui-suggest" ></span>').autocomplete(
                options).on('autocompleteresponse', function(event, ui) {
                var content = ui.content;
                $(this).autocomplete('validate', content);
            }).on('autocompleteselect', function(event, ui) {
                ui.item.value = ui.item.code;
                return $(this).autocomplete('setValue', ui.item);

            }).on('autocompletesearch', function(event, ui) {
                //支持多选
                return $(this).autocomplete('multiplesearch');
            });
        }

        var universalCode = function(el, options) {

            var tpl = '<div><div class="contract-item">' +
                '<span class="contract-width250">${code}</span>' +
                '<span style="border-right:none;">${name}</span>' +
                '</div></div>';

            var title = {
                code: '直播频道首拼音',
                name: '直播频道名称',
            };

            var getHtmlByData = function(data) {
                var htmls = [];
                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);

            universalCodeCreateSuggest(el, $.extend(true, {

                url: '/api/channel/codelist',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'key': term
                    };
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, item, {
                                name: item.name,
                                code: item.code,
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-qitan');
        };



        var qitanSuggest = function($inputs, options) {

            $inputs.each(function(index, element) {
                var self = this;
                qitan($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.id);
                        //console.log( $input.data('value'));
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };

        var universalCodeSuggest = function($inputs, options) {

            $inputs.each(function(index, element) {
                var self = this;
                universalCode($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.code);
                        //console.log($input.data('value'));
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };



        var alternatePlayCollection = function(el, options) {

            var tpl = '<div class="contract-item">' +
                '<span class="contract-width100" style="color:${needAlert}">${qipuId}</span>' +
                '<span class="contract-width150" style="color:${needAlert}">${displayName}</span>' +
                '<span class="contract-width60" style="color:${needAlert}">${channelName}</span>' +
                '<span class="contract-width120" style="color:${needAlert}">${copyrightEndTime}</span>' +
                '<span class="contract-width80" style="color:${needAlert}">${isPurchase}</span>' +
                '<span class="contract-width80" style="color:${needAlert}">${pagePublishStatus}</span>' +
                '</div>';

            var _ppsClientArr = [
                "ANDRIOD_PPSControl",
                "ANDROID_PAD_PPSControl",
                "IOS_JAILBREAK_PPSControl",
                "IPAD_PPSControl",
                "IPHONE_PPSControl",
                "MAC_PPSControl",
                "PC_CLIENT_PPSControl",
                "WIN8_PPSControl",
                "WINDOWS_PHONE_PPSControl"
            ];

            var _platClientArr = [
                "ANDRIOD_PPS",
                "ANDROID_PAD_PPS",
                "IOS_JAILBREAK_PPS",
                "IPAD_PPS",
                "IPHONE_PPS",
                "MAC_PPS",
                "PC_CLIENT_PPS",
                "WIN8_PPS",
                "WINDOWS_PHONE_PPS"
            ];

            var platformRefer = "platformRefer",
                platSettings = "platSettings",
                platforms = "platforms";

            var title = {
                qipuId: '奇谱ID',
                displayName: '显示名称',
                channelName: '频道',
                copyrightEndTime: '版权到期时间',
                isPurchase: '是否付费',
                pagePublishStatus: '发布状态'
            };

            var checkPlatforms = [];
            Ancestor.Dao.getType({
                type: 'PlayPlatform'
            }, function(json) {
                if (json.code == 'A00000') {
                    Ancestor.Config.PLATFORM_TYPE = json.data;
                    checkPlatforms = json.data;
                } else {
                    console.log('Fetch PlayPlatform failed');
                }
            });


            Ancestor.Dao.getType({
                type: 'PlatformRefer'
            }, function(json) {
                if (json.code == 'A00000') {
                    Ancestor.Config.PLATFORM_REFER = json.data;
                } else {
                    console.log('Fetch PlayPlatform failed');
                }
            });

            var decodePlayPlatform = function(elementChild) {
                var locationControl = null;
                var platformObject = {
                    platName: null,
                    locationArr: []
                }
                platformObject.platName = elementChild["play_platform"];
                platformObject.status = 'online';
                if (elementChild["default_control"] != null) {
                    if ("ONLINE" != elementChild["default_control"]["availabe_status"]) {
                        platformObject.status = "offline";
                    }
                }
                if ($.isArray(elementChild["region_control"])) {
                    $.each(elementChild["region_control"], function(indexRegion, regionElement) {
                        if ($.isArray(regionElement["location"])) {
                            $.each(regionElement["location"], function(j, child) {
                                if(child.hasOwnProperty("province_id")){
                                    if (child["province_id"] != 95 && child["province_id"]  != 148 && child["province_id"]  != 228) {
                                        locationControl = regionElement["location_control"];
                                        if (locationControl != null && "ONLINE" != locationControl["availabe_status"]) {
                                            platformObject.locationArr.push(child["province_id"]);
                                            console.log("break regionElement location");
                                        }
                                    }
                                }
                            })
                        }
                    })
                }
                return platformObject;
            };

            var checkPPSClient = function(data) {
                if (data.qipuId == '奇谱ID') {
                    data['needAlert'] = 0;
                    return data;
                }

                var ppsCheckList = [];
                $.each(_ppsClientArr, function(i, ppsKey) {
                    if (!data.hasOwnProperty(ppsKey) || data[ppsKey] == 0) {
                        ppsCheckList.push(ppsKey);
                    }
                });

                if (ppsCheckList.length > 0) {
                    data['needAlert'] = 'red';
                } else {
                    data['needAlert'] = 'black';
                }
                return data;
            };

            var checkQipuData = function(data) {
                var playControlArr = data.QIPUDATA.access_play_control;
                if ($.isArray(playControlArr)) {
                    var temp = {};
                    $.each(playControlArr, function(index, elementChild) {
                        var platformObject = decodePlayPlatform(elementChild);
                        if (platformObject.platName != null) {
                            temp[platformObject.platName] = platformObject;
                        }
                    });

                    var qipuPlatformData = [];
                    var qipuRegionData = [];
                    var hintMsgObj = {
                        missQIYIClient: false,
                        missPPSClient: false,
                        missQIYIRegion: false,
                        missPPSRegion: false
                    };
                    $.each(checkPlatforms, function(index, element) {
                        var ppsFlag = element.val.indexOf("PPS") !== -1;
                        if (!temp.hasOwnProperty(element.val) || temp[element.val].status != "online") {
                            qipuPlatformData.push(element.val);
                            if (ppsFlag) {
                                hintMsgObj.missPPSClient = true;
                            } else {
                                hintMsgObj.missQIYIClient = true;
                            }
                        }
                        if (temp.hasOwnProperty(element.val) && temp[element.val].locationArr.length > 0) {
                            qipuRegionData.push(element.val);
                            if (ppsFlag) {
                                hintMsgObj.missPPSRegion = true;
                            } else {
                                hintMsgObj.missQIYIRegion = true;
                            }
                        }
                    });

                    if (hintMsgObj.missPPSClient || hintMsgObj.missQIYIClient) {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.RED;
                    } else if (hintMsgObj.missPPSRegion || hintMsgObj.missQIYIRegion) {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.ORANGE;
                    } else {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.NORMAL;
                    }

                }

                return data;
            };

            var getHtmlByData = function(data) {

                if (typeof(data.copyrightEndTime) == "number" || typeof(data.copyrightBeginTime) == "number") {

                    if (data.copyrightEndTime == '-100' || data.copyrightBeginTime == '-100') {
                        data.copyrightEndTime = "永久版权";
                    } else if (new Date() > data.copyrightEndTime || new Date() < data.copyrightBeginTime) {
                        data.copyrightEndTime = "过期";
                    } else {
                        data.copyrightEndTime = Com.date.format(new Date(data.copyrightEndTime), "yyyy-MM-dd hh:mm:ss");
                    }
                }

                //if(data.copyrightEndTime=="过期")
                //  return '';

                switch (data.isPurchase) {
                    case 0:
                    case -100:
                        data.isPurchase = "免费";
                        break;
                    case 1:
                        data.isPurchase = "收费";
                        break;
                    case undefined:
                        data.isPurchase = ""
                        break;

                    default:
                        data.isPurchase = data.isPurchase + ""
                }

                switch (data.pagePublishStatus) {
                    case 0:
                        data.pagePublishStatus = "未发布";
                        break;
                    case 1:
                        data.pagePublishStatus = "已发布";
                        break;
                    case 2:
                        data.pagePublishStatus = "页面下线";
                        break;
                    case 3:
                        data.pagePublishStatus = "页面备用"
                        break;
                    case undefined:
                        data.pagePublishStatus = ""
                        break;

                    default:
                        data.pagePublishStatus = data.pagePublishStatus + "";
                }

                var htmls = [];
                data['needAlert'] = Ancestor.Config.APC_WARNING.NORMAL;

                if (data.hasOwnProperty('QIPUDATA')) {
                    data = checkQipuData(data);
                } else {
                    data = checkPPSClient(data);
                }

                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));

                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);
            createSuggest(el, $.extend(true, {

                //url: 'http://lego.iqiyi.com/suggest/simple-video-area',
                url: 'http://lego.iqiyi.com/apis/search/search-area',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                needFetchMore: true,
                needPreProcess: true,
                otherParam: $.extend({
                    t: 0,
                    filter_GTL_qipuId: 0,
                    //filter_EQI_contentType:1,
                    //'page.orderBy': "createTime",
                    //'page.order': "desc",
                    filter_GEL_duration: 30000,
                    //filter_EQI_pagePublishStatus:1,
                    //filter_INI_isPurchase : "0,-100",
                    //filter_GTI_copyrightOwnerId : 0,
                    //filter_EQI_PadIosControl:1,
                    //filter_EQI_PhoneAndroidControl:1,
                    //filter_EQI_PhoneIosControl:1,
                    //filter_EQI_PcControl:1,
                    //filter_EQI_TvControl:1,
                    //filter_EQI_PcClientControl:1,
                    //filter_EQI_H5Control:1,
                    //filter_EQI_PadAndroidControl:1,
                    //filter_EQI_PadWebControl:1,
                    //region:1,
                    'page.pageSize': 10
                        //                    filter_EQI_ANDRIOD_PPSControl: 1,
                        //                    filter_EQI_ANDROID_PAD_PPSControl: 1,
                        //                    filter_EQI_IOS_JAILBREAK_PPSControl: 1,
                        //                    filter_EQI_IPAD_PPSControl: 1,
                        //                    filter_EQI_IPHONE_PPSControl: 1,
                        //                    filter_EQI_MAC_PPSControl: 1,
                        //                    filter_EQI_PC_CLIENT_PPSControl: 1,
                        //                    filter_EQI_WIN8_PPSControl: 1,
                        //                    filter_EQI_WINDOWS_PHONE_PPSControl: 1,
                        //                    needCookie: true

                    //   pps region 限制
                    //region_ANDROID_PAD_PPS:0,
                    //region_WIN8_PPS:0,
                    //region_MAC_PPS:0,
                    //region_WINDOWS_PHONE_PPS:0,
                    //region_ANDRIOD_PPS:0,
                    //region_IOS_JAILBREAK_PPS:0,
                    //region_IPAD_PPS:0,
                    //region_IPHONE_PPS:0,
                    //region_PC_CLIENT_PPS:0,
                    //   qiyi region 限制
                    //region_ANDROID_PAD_IQIYI:1,
                    //region_ANDROID_PHONE_IQIYI:1,
                    //region_H5_QIYI:1,
                    //region_IOS_PAD_IQIYI:1,
                    //region_IOS_PHONE_IQIYI:1,
                    //region_PAD_WEB_QIYI:1,
                    //region_PC_CLIENT_IQIYI:1,
                    //region_PC_QIYI:1,
                    //region_TV_IQIYI:1,
                }, options.params),
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'filter_LIKES_displayName': term
                    };
                },

                fetchMore: function(data, callback) {
                    var self = this;
                    self.count = 0;
                    self.ret = [];
                    self.data = data;
                    $.each(data, function(i, item) {
                        Ancestor.Dao.getQipuDataById(item, function(json, t) {
                            if (json) {
                                t.QIPUDATA = json;
                            }
                            self.ret.push(t);
                            self.count++;
                            if (self.count == self.data.length) {
                                callback(self.ret);
                            }
                        });
                    });
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data.result, function(item) {
                            ret.push($.extend(true, item, {
                                name: item.displayName,
                                id: item.qipuId
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-backup');
        };

        var alternatePlayCollectionSuggest = function($inputs, options) {
            $inputs.each(function(index, element) {
                var self = this;
                alternatePlayCollection($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.qipuId);
                        //console.log( $input.data('value'));

                        var temp = data.item;
                        data.item = {};

                        data.item['qipuId'] = temp['qipuId'];
                        data.item['displayName'] = temp['displayName'];
                        data.item['contentType'] = temp['contentType'];
                        data.item['duration'] = temp['duration'];
                        data.item['needAlert'] = temp['needAlert'];
                        temp = {};

                        var alternatePlayCollection = $('input[name="alternatePlayCollection"]').val();
                        //console.log(alternatePlayCollection);
                        if (alternatePlayCollection) {
                            alternatePlayCollection = JSON.parse(alternatePlayCollection);
                            var has = false,
                                i;

                            for (var i in alternatePlayCollection) {
                                if (alternatePlayCollection[i].qipuId == data.item.qipuId) {
                                    has = 1;
                                    break;
                                }
                            }

                            i = parseInt(i) + 1;

                            if (!has) {
                                var msg = null;
                                if (data.item.needAlert == Ancestor.Config.APC_WARNING.RED) {
                                    msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端没有上线，但会在PPS平台播出，是否确认添加？";
                                } else if (data.item.needAlert == Ancestor.Config.APC_WARNING.ORANGE) {
                                    msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端有地域播控，但会在PPS平台全地域播出，是否确认添加？";
                                } else {
                                    alternatePlayCollection[i] = data.item;

                                    $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
                                    alternatePlayCollectionAppend({
                                        qipuId: data.item.qipuId
                                    });
                                }

                                if (msg) {
                                    SystemDialog.queryConfirm(msg, function(flag) {
                                        if (flag === true) {
                                            alternatePlayCollection[i] = data.item;

                                            $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));

                                            alternatePlayCollectionAppend({
                                                qipuId: data.item.qipuId
                                            });
                                        }
                                    });
                                }
                            }

                        } else {
                            alternatePlayCollection = {};

                            var msg = null;
                            if (data.item.needAlert == Ancestor.Config.APC_WARNING.RED) {
                                msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端没有上线，但会在PPS平台播出，是否确认添加？";
                            } else if (data.item.needAlert == Ancestor.Config.APC_WARNING.ORANGE) {
                                msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端有地域播控，但会在PPS平台全地域播出，是否确认添加？";
                            } else {
                                alternatePlayCollection[0] = data.item;

                                $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
                                alternatePlayCollectionAppend({
                                    qipuId: data.item.qipuId
                                });
                            }

                            if (msg) {
                                SystemDialog.queryConfirm(msg, function(flag) {
                                    if (flag === true) {
                                        alternatePlayCollection[0] = data.item;

                                        $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));

                                        alternatePlayCollectionAppend({
                                            qipuId: data.item.qipuId
                                        });
                                    }
                                });
                            }
                        }
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };


        var alternatePlayCollectionAppend = function(v) {
            $('#alternatePlayCollectionIds').append('<span class="ui-suggest-value tagmanagerTag" data-id="' + v.qipuId + '">' + v.qipuId + '<a class="tagmanagerRemoveTag"  onclick="Ancestor.Util.removeAlternatePlayCollection(this)"  title="Remove" href="javascript:;">x</a></span>');
            $('input[name="alternatePlayCollectionInput"]').attr('disabled','disabled');;
        };

        // 删除备播库
        removeAlternatePlayCollection = function(obj) {

            var alternatePlayCollection = $('input[name="alternatePlayCollection"]').val(),
                AlternatePlayCollectionId = $(obj).parent().attr('data-id'),
                alternatePlayCollectionTmp = {};

            alternatePlayCollectionTmp = alternatePlayCollection = JSON.parse(alternatePlayCollection);

            for (var i in alternatePlayCollectionTmp) {
                if (alternatePlayCollectionTmp[i].qipuId == AlternatePlayCollectionId) {
                    delete alternatePlayCollection[i];
                    break;
                }
            }

            if ($.isEmptyObject(alternatePlayCollection)) {
                $('input[name="alternatePlayCollection"]').val('');
                $('input[name="alternatePlayCollectionInput"]').removeAttr('disabled');;
            } else {
                $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
            }

            $(obj).parent().remove();
        };



        var getAuth = function(str) {

            var auth = {
                    'sign': '',
                    'clientTime': '',
                    'from': ''
                },
                time = parseInt(new Date().getTime() / 1000);

            auth.from = Ancestor.Config.EPG_AUTH.From;
            auth.clientTime = time;
            auth.sign = md5(str + time + Ancestor.Config.EPG_AUTH.key);

            //console.log(auth);            
            return auth;

        };

        return {
            imageCrop: imageCrop,
            authorization: authorization,
            getParam: getParam,
            getUrlId: getUrlId,
            fillFieldNameWhenChangeSelect: fillFieldNameWhenChangeSelect,
            limitWordCount: limitWordCount,
            getUploadFiles: getUploadFiles,
            isNormal: isNormal,
            openDlg: openDlg,
            qitanSuggest: qitanSuggest,
            universalCodeSuggest: universalCodeSuggest,
            imageObjectEcho: imageObjectEcho,
            getAuth: getAuth,
            alternatePlayCollectionSuggest: alternatePlayCollectionSuggest,
            alternatePlayCollectionAppend: alternatePlayCollectionAppend,
            removeAlternatePlayCollection: removeAlternatePlayCollection,
        };


    })();

});

define(
    '../epg2/EpgWeb',['require','exports','module'],function(require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };

        EpgWeb.Constant = {
            //baseApiUrl:"http://test.admin.epg.qiyi.domain/api/",
            baseApiUrl: "/api/",
            thirdUrl_audit_people: "http://lego.iqiyi.com/suggest/audit-people",
            originalUrl: "http://10.23.84.18:8500/",
            third_location_url:"http://lego.iqiyi.com/suggest/region",
            thirdUrl_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/get_id_by_name",
            thirdUrl_add_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/add_resource",
            thirdUrl_video_url: "http://lego.iqiyi.com/suggest/simple-video",
            thirdUrl_album_url: "http://lego.iqiyi.com/suggest/album",
            thirdUrl_playlist_url: "http://lego.iqiyi.com/suggest/playlist",
            thirdUrl_channel_url:"http://lego.iqiyi.com/apis/channel/list",
            thirdUrl_video_area_url: "http://lego.iqiyi.com/suggest/simple-video-area",
            thirdUrl_album_area_url: "http://lego.iqiyi.com/suggest/album-area",
            thirdUrl_apis_search_area_url: "http://lego.iqiyi.com/apis/search/search-area",
            thirdUrl_category_first_list_url:"http://lego.iqiyi.com/apis/category/live-first-list",
            // use for child secLv thirdLv
            thirdUrl_category_child_list_url: "http://lego.iqiyi.com/category/list",
            thirdUrl_passport_url:"http://passport.qiyi.domain/apis/internal/user_info.action",
            devMode: auth.dev()
        }
        EpgWeb.urlConfig = (function () {
            var useUrl = EpgWeb.Constant.baseApiUrl;
            var programListUrl = useUrl + "program/list";
            var programListSortUrl = useUrl + "program/listSort";
            var programAddUrl = useUrl + "program/add";
            var programDelUrl = useUrl + "program/delete";
            var programEditUrl = useUrl + "program/edit";
            var programLogUrl = useUrl + "program/loglist";
            var configsUrl = useUrl + "configs";
            var channelListUrl = useUrl + "channel/list";
            var programSyncUrl = useUrl + "program/syncTVMao";
            var redirectUrl = useUrl + "redirect";
            var channelGetUrl = useUrl + "channel/get";
            var queryPuYuUrl = useUrl + "program/queryPuYu";
            var carouselRuleListUrl = useUrl + "carousel/get";
            var carouselRuleDelUrl = useUrl + "carousel/del";
            var carouselRuldAddUrl = useUrl + "carousel/create";
            var programLiveQueryUrl = useUrl + "program/liveQuery";
            var programMoveUrl = useUrl + "program/move";
            var programToggleLockUrl = useUrl + "program/toggleLock";
            var programBatchAddUrl = useUrl + "program/batchAdd";
            var carouselEpisodeBatchAddUrl = useUrl + "carousel/carouselEpisode/batchAdd";
            var carouselEpisodeBatchDelUrl= useUrl + "carousel/carouselEpisode/batchDel";
            var carouselEpisodeListUrl= useUrl + "carousel/carouselEpisode/list";
            var carouselEpisodeIndexMoveUrl= useUrl + "carousel/carouselEpisode/indexMove";
            var carouselEpisodeIndexMoveByIndexUrl= useUrl + "carousel/carouselEpisode/indexMove/byIndex";
            var programDaySortUrl = useUrl + "program/daySort";
            var programIndexMoveUrl = useUrl + "program/indexMove";
            var programBatchDelUrl = useUrl + "program/batchDel";
            var platSettingsGetUrl = useUrl + "channel/getPlatSettings";
            var yesterdayEndTimeUrl = useUrl + "program/yesterdayEndTime";
            var automationAddUrl = useUrl + "carousel/automation/add";
            var automationDelUrl = useUrl + "carousel/automation/del";
            var automationListUrl = useUrl + "carousel/automations";
            var automationMoveUrl = useUrl + "carousel/automation/indexMove";
            var automationMoveByIndexUrl = useUrl + "carousel/automation/indexMove/byIndex";
            var automationChangeStatusUrl = useUrl + "carousel/automation/changeStatus";
            var getBroadcastControlsUrl = useUrl+"broadcast/controls";
            var reservation_create_Url = useUrl+ "reservation";
            var reservation_del_Url = useUrl+ "reservation/del";
            var reservation_edit_Url = useUrl+"reservation/edit";
            var reservation_get_Url = useUrl+ "reservations";
            var setBroadcastControlAllUrl= useUrl+"broadcast/controlall";
            var setBroadcastControlUrl  = useUrl+"broadcast/control";
            var platSettingsSaveUrl =  useUrl+"channel/savePlatSettings";
            var programBroadcastControlUrl =  useUrl+"program/broadcast/control";
            var programForceCheckUrl = useUrl + "program/forceCheck";
            var advertModifyUrl  = useUrl + "advert/modify";
            var directorCreateUrl =  useUrl + "director/create";
            var notifyAlertUrl = useUrl + "notify/alertPlatform";
            function getQiPuBaseUrl(qipuId){
                var plusUrl = EpgWeb.Constant.devMode ? "http://qipu-test.qiyi.domain/int/entity/nocache/@.json" : "http://qipu.qiyi.domain/int/entity/nocache/@.json";
                return plusUrl.replace("@", "" + qipuId);
            }
            return {
                programList: programListUrl,
                programListSortUrl: programListSortUrl,
                programAdd: programAddUrl,
                programDel: programDelUrl,
                programEdit: programEditUrl,
                programLog:programLogUrl,
                programForceCheck:programForceCheckUrl,
                configs: configsUrl,
                channelList: channelListUrl,
                channelGet: channelGetUrl,
                programSyncUrl: programSyncUrl,
                queryPuYu: queryPuYuUrl,
                carouselRuleListUrl: carouselRuleListUrl,
                carouselRuleDelUrl: carouselRuleDelUrl,
                carouselRuldAddUrl: carouselRuldAddUrl,
                carouselEpisodeBatchAddUrl:carouselEpisodeBatchAddUrl,
                carouselEpisodeBatchDelUrl:carouselEpisodeBatchDelUrl,
                carouselEpisodeListUrl:carouselEpisodeListUrl,
                carouselEpisodeIndexMoveUrl:carouselEpisodeIndexMoveUrl,
                carouselEpisodeIndexMoveByIndexUrl:carouselEpisodeIndexMoveByIndexUrl,
                programLiveQueryUrl: programLiveQueryUrl,
                programMoveUrl: programMoveUrl,
                programToggleLockUrl: programToggleLockUrl,
                programDaySortUrl: programDaySortUrl,
                programBatchAddUrl: programBatchAddUrl,
                programIndexMoveUrl: programIndexMoveUrl,
                programBatchDelUrl: programBatchDelUrl,
                platSettingsGetUrl: platSettingsGetUrl,
                yesterdayEndTimeUrl: yesterdayEndTimeUrl,
                automationAddUrl: automationAddUrl,
                automationDelUrl: automationDelUrl,
                automationListUrl: automationListUrl,
                automationMoveUrl: automationMoveUrl,
                automationChangeStatusUrl: automationChangeStatusUrl,
                reservationCreate:reservation_create_Url,
                reservationDel:reservation_del_Url,
                reservationGet:reservation_get_Url,
                getBroadcastControls:getBroadcastControlsUrl,
                reservationEdit:reservation_edit_Url,
                setBroadcastControlAllUrl:setBroadcastControlAllUrl,
                setBroadcastControl:setBroadcastControlUrl,
                platSettingsSaveUrl:platSettingsSaveUrl,
                programBroadcastControlUrl:programBroadcastControlUrl,
                redirect: redirectUrl,
                advertModifyUrl:advertModifyUrl,
                directorCreateUrl:directorCreateUrl,
                notifyAlertUrl:notifyAlertUrl,
                getQiPuBaseUrl:getQiPuBaseUrl
            }
        })();

        EpgWeb.ajaxQueue = (function () {
            var entity = this;
            var taskArr = [];
            var batchArr = [];
            var timerId = -1;
            var errorCollectArr = [];
            var afterCompleteArr = [];
            var status = -2;
            var checkComplete = function () {
                switch (status) {
                    case 1:
                        clearInterval(timerId);
                        timerId = -1
                        if (errorCollectArr.length > 0) {
                            var totalError = errorCollectArr.join("\n");
                            errorCollectArr = [];
                            EpgWeb.Plugin.showTips({
                                content: totalError,
                                type: "error"
                            })
                        }
                        status = 2;
                        loadComplete();
                        batchComplete();
                        break;
                    case -1:
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                var ajaxData = obj.ajaxData;
                                $.ajax({
                                    type: ajaxData.type,
                                    url: ajaxData.url,
                                    dataType: ajaxData.dataType,
                                    beforeSend: function (request) {
                                        request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                                    },
                                    data: ajaxData.data,
                                    success: function (data) {
                                        var tempTarget = findTaskByRegName(obj.regName);
                                        if (tempTarget.needRemove == true) {
                                            removeTask(obj.regName);
                                        } else {
                                            tempTarget.responseData = data;
                                        }
                                        if (ajaxData.success != null) {
                                            ajaxData.success(data);
                                        }
                                    },
                                    error: function (data) {
                                        if (ajaxData.error != null) {
                                            ajaxData.error(data);
                                        }
                                        errorCollectArr.push(obj.regName + " 请求失败")
                                        removeTask(obj.regName)
                                    }
                                });
                            }
                        })
                        status = 0;
                        timerId = setInterval(checkComplete, 16);
                        break;
                    case 0:
                        var allComplete = true;
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                allComplete = false;
                                return true;
                            }
                        });
                        if (allComplete) {
                            status = 1;
                        }
                        break;
                }
            }

            var batchComplete = function () {
                var tempArr = batchArr;
                batchArr =[];
                while (tempArr.length > 0) {
                    var batchRequestData = tempArr.pop();
                    batchRequestData.handler({"originalArr": batchRequestData.originalArr,
                            "acceptArr": batchRequestData.acceptMsgArr}
                    );
                }
            }

            var loadComplete = function () {
                console.log("loadComplete over");
                var tempArr = afterCompleteArr;
                afterCompleteArr = [];
                while (tempArr.length > 0) {
                    var excuteFunc = tempArr.shift();
                    excuteFunc.call();
                }
            }

            var push = function (regName, ajaxData, responseData, needRemove){
                if (typeof(needRemove) != "boolean") {
                    needRemove = needRemove == null ? false : true
                }
                taskArr.push({"regName": regName, "ajaxData": ajaxData, "responseData": responseData, "needRemove": needRemove})
            }

            var batchRequest = function (regName, ajaxData, sendDataArr, handler){
                var acceptMsgArr = [];
                var batchRequestData = {"originalArr": sendDataArr, "acceptMsgArr": acceptMsgArr, handler: handler }
                batchArr.push(batchRequestData)
                $.each(sendDataArr, function (index, obj) {
                    taskArr.push(
                        {
                            "regName": regName + "_" + index,
                            "ajaxData": {
                                type: ajaxData.type,
                                url: ajaxData.url,
                                dataType: ajaxData.dataType,
                                data: obj,
                                success: function (data) {
                                    var formatData = null;
                                    if (data != null) {
                                        formatData = {"nodeIndex": index, "operationSuccess": false, "responseData": data, "msg": data.msg};
                                        if (data.code == "A00000") {
                                            formatData.operationSuccess = true;
                                        }
                                    } else {
                                        formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    }
                                    acceptMsgArr.push(formatData)
                                },
                                error: function (data) {
                                    var formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    acceptMsgArr.push(formatData);
                                }
                            },
                            "needRemove": true
                        });
                })
            }

            var startLoad = function(){
                if (status != -2 && status != 2) {
                    return false;
                }
                status = -1;
                console.log(JSON.stringify(taskArr) );
                checkComplete();
                return true;
            }

            var findResponseData = function (regName) {
                var task = findTaskByRegName(regName);
                if (task == null) {
                    return null;
                }
                return task.responseData;
            }
            var removeTask = function (regName) {
                var task = findTaskByRegName(regName);
                if (task != null) {
                    var taskIndex = taskArr.indexOf(task)
                    taskArr.splice(taskIndex, 1);
                }
            }

            var findTaskByRegName = function(regName) {
                if (taskArr.length == 0) {
                    return null;
                }
                var returnTarget = null;
                $.each(taskArr, function (index, obj) {
                    if (obj.regName == regName) {
                        returnTarget = obj;
                        return false;
                    }
                })
                return returnTarget;
            }

            var afterLoadComplete = function (callback) {
                if (typeof(callback) == "function") {
                    afterCompleteArr.push(callback);
                }
            }

            var isRunning = function () {
                return status == 0;
            }

            function getTaskArr(){
                return [].concat(taskArr);
            }

            function getStatus(){
                return status;
            }

            return {
                startLoad:startLoad,
                findResponseData:findResponseData,
                findTaskByRegName:findTaskByRegName,
                batchRequest:batchRequest,
                push:push,
                isRunning:isRunning,
                removeTask:removeTask,
                afterLoadComplete:afterLoadComplete,
                getTaskArr:getTaskArr,
                getStatus:getStatus
            }
        })();
    }
);
define(
    '../epg2/EpgWeb.Util',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Util = $.extend(true, {}, Ancestor.Util, {
            tranDurationFormat: function (duration) {
                var darArr = [];
                darArr.push(duration % 60);
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 60);
                }
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 24);
                }
                duration = ( duration - duration % 24) / 24;
                if (duration > 0) {
                    darArr.push(duration);
                }
                var retValue = "";
                switch (darArr.length) {
                    case 4:
                        retValue = darArr[3] + "天";
                    case 3:
                        retValue += darArr[2] + "时";
                    case 2:
                        retValue += darArr[1] + "分";
                    case 1:
                        retValue += darArr[0] + "秒";
                        break;
                }
                return retValue;
            },
            makeUpRedirect: function (url, method, params, needCookie) {
                var requestData = {url: url, type: method, params: params};
                if (needCookie === true) {
                    requestData.needCookie = true;
                }
                return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
            },
            quickDateFormat: function (startTime) {
                return startTime.getFullYear() + "-" +
                    (startTime.getMonth() < 9 ? "0" + (startTime.getMonth() + 1) : (startTime.getMonth() + 1) ) + "-" +
                    (startTime.getDate() < 10 ? "0" + startTime.getDate() : startTime.getDate() );
            },
            bindDateMax: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },
            setZeroTime: function (checkTime) {
                checkTime.setSeconds(0);
                checkTime.setMinutes(0);
                checkTime.setHours(0);
                checkTime.setMilliseconds(0);
            },
            setDayLastTime: function (checkTime) {
                checkTime.setSeconds(59);
                checkTime.setMinutes(59);
                checkTime.setHours(23);
                checkTime.setMilliseconds(0);
            },

            bindDate: function (nameMin, nameMax, plusData) {
                var options1 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                }
                var options2 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                }
                if (plusData != null && plusData.hasOwnProperty("slider")) {
                    options1.controlType = "slider";
                    options2.controlType = "slider";
                }
                $("input[name=" + nameMin + "]").datetimepicker(options1)
                $("input[name=" + nameMax + "]").datetimepicker(options2)
                if (plusData != null) {
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },



            bindDateMin: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                }
            },
            createPageBean: function () {
                return (function () {
                    var source = [];
                    var dataLength = source.length;
                    var rowNum = 10;
                    var total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    var cur = 1;

                    function goToFirst() {
                        return goToUser(1);
                    }

                    function goToLast() {
                        return goToUser(total);
                    }

                    function goToUser(toPage) {
                        if (toPage < 1) toPage = 1;
                        if (toPage > total) toPage = total;
                        cur = toPage;
                        var end = cur * rowNum > dataLength ? dataLength : cur * rowNum;
                        var showData = source.slice((cur - 1) * rowNum, end);
                        return {"total": total, "page": cur, "records": dataLength, "rows": showData};
                    }

                    function getCur() {
                        return goToUser(cur);
                    }

                    function goNext() {
                        return goToUser(cur + 1);
                    }

                    function goPrev() {
                        return goToUser(cur - 1);
                    }

                    function setNewData(newData, newRowNum) {
                        source = newData == null ? [] : newData;
                        if (newRowNum != null && newRowNum > 0) {
                            rowNum = newRowNum;
                        }
                        dataLength = source.length;
                        total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    }

                    function addNewOne(newOne) {
                        source.push(newOne);
                        setNewData(source, rowNum);
                    }

                    function delOne(delOne) {
                        var targetIndex = source.indexOf(delOne);
                        if (targetIndex > -1) {
                            source.splice(targetIndex, 1);
                            setNewData(source, rowNum);
                        }
                    }

                    function getSource() {
                        return [].concat(source);
                    }

                    function findData(keyName, value) {
                        var ret = null;
                        if (value == null || keyName == null) {
                            return null;
                        }
                        $.each(source, function (i, element) {
                            if (element != null && element[keyName] == value) {
                                ret = element;
                                return true;
                            }
                        })
                        return ret;
                    }

                    function sortData(func) {
                        if (typeof( func ) == "function") {
                            source.sort(func);
                        }
                    }

                    return {
                        goToFirst: goToFirst,
                        goToLast: goToLast,
                        goToUser: goToUser,
                        goNext: goNext,
                        goPrev: goPrev,
                        getCur: getCur,
                        setNewData: setNewData,
                        addNewOne: addNewOne,
                        delOne: delOne,
                        getSource: getSource,
                        findData: findData,
                        sortData: sortData
                    }
                })()
            },
            pageBeanPageHandler: function (gridId, pageId, pageBean, pgButton) {
                var retValue = null;
                switch (pgButton) {
                    case "next_" + pageId:
                        retValue = pageBean.goNext()
                        break;
                    case "prev_" + pageId:
                        retValue = pageBean.goPrev()
                        break;
                    case "last_" + pageId:
                        retValue = pageBean.goToLast()
                        break;
                    case "user":
                        retValue = pageBean.goToUser(parseInt($("#gbox_" + gridId + " .ui-pg-input").val()));
                        break;
                    case "first_" + pageId:
                        retValue = pageBean.goToFirst();
                        break;
                }
                return retValue
            },
            transGetParams: function (params) {
                var str = "";
                for (var key in params) {
                    str += key + "=" + params[key] + "&";
                }
                if (str.length > 0) {
                    str = str.substr(0, str.length - 1);
                }
                return str;
            },

            formatDateTimeFormat: function (myDate) {
                var year = myDate.getFullYear();
                var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
                var day = ("0" + myDate.getDate()).slice(-2);
                var h = ("0" + myDate.getHours()).slice(-2);
                var m = ("0" + myDate.getMinutes()).slice(-2);
                var s = ("0" + myDate.getSeconds()).slice(-2);
                return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s;
            },
            getQueryComponent: function (handlerObj) {
                return {
                    source: null,
                    total: 0,
                    completeNum: 0,
                    handlerObj: handlerObj,
                    doInit: function (newArr) {
                        var self = this;
                        self.source = newArr;
                        self.total = newArr.length;
                        self.completeNum = 0;
                        self.doSubmit();
                    },
                    doSubmit: function () {
                        var self = this;
                        self.doBefore();
                        $.each(self.source, function (i, element) {
                            self.doSingle(element, function () {
                                self.notifyHandler()
                            });
                        })
                    },
                    doBefore: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doBefore")) {
                                self.handlerObj.doBefore();
                            }
                        }
                    },
                    doAfter: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doAfter")) {
                                self.handlerObj.doAfter();
                            }
                        }
                    },
                    doSingle: function (element, notifyHandler) {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doSingle")) {
                                self.handlerObj.doSingle(element, notifyHandler);
                            }
                        }
                    },
                    notifyHandler: function () {
                        var self = this;
                        self.completeNum++;
                        if (self.completeNum == self.total) {
                            self.doAfter();
                        }
                    }
                };
            },
            createWeekManager: function (labelArr) {
                return (function ($labelArr) {
                    var focusStartTime = null;
                    var selectDateTime = null;
                    var weekday = "星期日,星期一,星期二,星期三,星期四,星期五,星期六".split(",");

                    function preWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() - 7 * 86400 * 1000));
                        }
                    }

                    function nextWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() + 7 * 86400 * 1000));
                        }
                    }

                    function updateWeek(startTime) {
                        if (startTime != null) {
                            focusStartTime = startTime;
                        }
                        var tempStartTime = new Date(focusStartTime.getTime());
                        $labelArr.each(function (i, element) {
                            var lDateFormat = EpgWeb.Util.quickDateFormat(tempStartTime);
                            $(element).attr("query-date", lDateFormat);
                            $(element).removeClass("selected");
                            $(element).html(weekday[tempStartTime.getDay()] + "<br>" + lDateFormat);
                            if (lDateFormat == selectDateTime) {
                                $(element).addClass("selected");
                            }
                            tempStartTime.setTime(tempStartTime.getTime() + 86400 * 1000);
                        })
                    }

                    function quickToCurrentWeek() {
                        var current = new Date();
                        var currentIndex = -1;
                        if (current.getDay() == 0) {
                            currentIndex = 6;
                        } else {
                            currentIndex = current.getDay() - 1;
                        }
                        selectDateTime = EpgWeb.Util.quickDateFormat(current)
                        updateWeek(new Date(current.getTime() - currentIndex * 86400 * 1000));
                        //updateTableByDate(selectDateTime);
                        return selectDateTime;
                    }

                    return{
                        preWeek: preWeek,
                        nextWeek: nextWeek,
                        quickToCurrentWeek: quickToCurrentWeek
                    }
                })(labelArr)
            },
            createHeartBeatUtil: function () {
                return  (function () {
                    var params = {
                        startTime: 0,
                        isStarted: false,
                        indexId: 0,
                        dataArr: []
                    }

                    function doHeartBeat() {
                        var curTime = Date.now();
                        var cpArr = [].concat(params.dataArr);

                        $.each(cpArr, function (i, element) {
                            tick(element, curTime);
                        })
                    }

                    function start() {
                        if (params.isStarted) {
                            console.log("has started");
                            return;
                        }
                        params.startTime = Date.now();
                        params.isStarted = true;
                        $.each(params.dataArr, function (i, elment) {
                            elment.lastTime = params.startTime;
                        })
                        setInterval(function () {
                            doHeartBeat();
                        }, 160)
                    }

                    function tick(element, curTime) {
                        if (element.block || element.stop) {
                            return;
                        }
                        if (element.lastTime + element.gapTime < curTime) {
                            element.lastTime = curTime;
                            element.options.handler();
                            if (element.options.needBlock) {
                                element.block = true;
                            }
                        }
                    }

                    function pushTask(taskObj) {
                        params.indexId++;
                        var taskOptions = {
                            block: false,
                            stop: taskObj.stop || false,
                            options: taskObj,
                            id: params.indexId,
                            lastTime: 0
                        }
                        taskOptions.gapTime = accountGapTime(taskObj)
                        if (params.isStarted) {
                            taskOptions.lastTime = Date.now() + 100;
                        }
                        params.dataArr.push(taskOptions);
                        return taskOptions;
                    }

                    function accountGapTime(taskObj) {
                        var time = [0, 0, 0, 0];//ms,s,m,h
                        if ("ms" in taskObj.gap) {
                            time[0] = taskObj.gap.ms;
                        }
                        if ("s" in taskObj.gap) {
                            time[1] = taskObj.gap.s;
                        }
                        if ("m" in taskObj.gap) {
                            time[2] = taskObj.gap.m;
                        }
                        if ("h" in taskObj.gap) {
                            time[3] = taskObj.gap.h;
                        }
                        return  time[0] + time[1] * 1000 + time[2] * 60000 + time[3] * 3600000;
                    }

                    return {
                        start: start,
                        doHeartBeat: doHeartBeat,
                        pushTask: pushTask,
                        tick: tick
                    }
                })();
            },
            notifyAlert: function (sendData, handler) {
                EpgWeb.Dao.notifyAlert(sendData, function (rdata) {
                    handler(rdata)
                });
            },
            getCurrentUserEntity:function(){
                var ret = null;
                try{
                    ret =auth.baseInfo.authInfo;
                }catch (e){
                    console.warn(e);
                }
                return ret
            }
        });
    }
);
define(
    '../epg2/EpgWeb.Plugin',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Plugin = {
            showTips: function (options) {
                if (!options.hasOwnProperty("type")) {
                    options.type = "success";
                }
                if ($(document).tips != null) {
                    $(document).tips(options)
                }
                if ($(document).tip != null) {
                    $(document).tip(options)
                } else {
                    console.log("no tips plugin " + options);
                }
            },
            Validate: (function () {
                var reg1 = /^\d+$/;
                var reg3 = /^[1-9]\d*$/;
                var reg2 = /^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]) ([0-2][0-9]):([0-5][0-9]):([0-5][0-9])$/;
                var reg4 = /^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;
                var _defaultHandler = function(msg){
                    EpgWeb.Plugin.showTips({type: "error", content: msg})
                }
                var _bindHandler = null;
                var checkObj = {
                    self_design: function (checkData, checkValue) {
                        return checkData.checkCall(checkData, checkValue)
                    },
                    date: function (checkData, checkValue) {
                        return checkDateFormat(checkValue);
                    },
                    not_empty: function (checkData, checkValue) {
                        return checkValue != null && $.trim(checkValue).length > 0;
                    },
                    eq: function (checkData, checkValue) {
                        return checkValue === checkData.other;
                    },
                    ne: function (checkData, checkValue) {
                        return checkValue !== checkData.other;
                    },
                    ge: function (checkData, checkValue) {
                        return  checkValue >= checkData.other;
                    },
                    gt: function (checkData, checkValue) {
                        return  checkValue > checkData.other;
                    },
                    lt: function (checkData, checkValue) {
                        return checkValue < checkData.other;
                    },
                    le: function (checkData, checkValue) {
                        return checkValue <= checkData.other;
                    },
                    positive:function(checkData, checkValue) {
                        return  checkPositive(checkValue)
                    },
                    number: function (checkData, checkValue) {
                        return checkNum(checkValue);
                    },
                    endsWith: function (checkData, checkValue) {
                        return checkValue != null && typeof(checkValue) == "string" && checkValue.slice(-(checkData.other.length)) == checkData.other;
                    }
                }

                function checkNum(checkString) {
                    return reg1.test(checkString)
                }

                function checkDateFormat(checkString) {
                    return reg2.test(checkString)
                }

                function checkPositive(checkString) {
                    return reg3.test(checkString)
                }

                function defaultHandler(msg) {
                    if(_bindHandler != null){
                        _bindHandler(msg);
                    }
                }

                function batchCheck(checkArr) {
                    if (checkArr == null) {
                        checkArr = [];
                    }
                    if (checkArr.length == 0) {
                        return true;
                    }
                    var flag = false;
                    $.each(checkArr, function (index, checkData) {
                        flag = baseCheck(checkData);
                        if (!flag) {
                            return false;
                        }
                    })
                    return flag;
                }

                function baseCheck(checkData) {
                    var flag = false;
                    //$.isArray(checkData.value )
                    if (!(checkData.value instanceof Array)) {
                        checkData.value = [checkData.value];
                    }
                    //$.isArray(checkData.error )
                    if (!(checkData.error instanceof Array)) {
                        checkData.error = [checkData.error];
                    }
                    if (checkData.handler == null) {
                        checkData.handler = defaultHandler;
                    }
                    $.each(checkData.value, function (index, checkValue) {
                        if (checkObj.hasOwnProperty(checkData.type)) {
                            flag = checkObj[checkData.type](checkData, checkValue);
                        }
                        if (!flag) {
                            var hint = checkData.error.length == checkData.value.length ? checkData.error[index] : checkData.error[0];
                            checkData.handler(hint);
                            return false;
                        }
                    })
                    return flag
                }
                function bindDefaultHandler(func){
                    _bindHandler = func;
                }
                return {
                    baseCheck: baseCheck,
                    batchCheck: batchCheck,
                    checkDateFormat: checkDateFormat,
                    checkNum: checkNum,
                    bindDefaultHandler:bindDefaultHandler
                }
            })(),

            tableToExcel: (function () {
                var uri = 'data:application/vnd.ms-excel;base64,',
                    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                    base64 = function (s) {
                        return window.btoa(unescape(encodeURIComponent(s)))
                    },
                    format = function (s, c) {
                        return s.replace(/{(\w+)}/g,
                            function (m, p) {
                                return c[p];
                            })
                    };

                return function (table, name) {
                    if (!table.nodeType) table = document.getElementById(table)
                    var ctx = {
                        worksheet: name || 'Worksheet',
                        table: table.innerHTML
                    }
                    window.location.href = uri + base64(format(template, ctx))
                }
            })()
        };

    }
);
define(
    '../epg2/EpgWeb.Dao',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Dao = $.extend({}, Ancestor.Dao, {
            cfgName: {
                LiveType: "LiveType",
                LogType: "LogType",
                episodeGradeType: "EpisodeGradeType",
                liveProgramType: "LiveProgramType",
                liveChannelType: "LiveChannelType",
                getChannel: "getChannel"
            },
            channelId: null,
            getDataByName: function (targetName) {
                var responseData = EpgWeb.ajaxQueue.findResponseData(targetName);
                return responseData;
            },
            sendAjax: function (url, method, data, callback, authUrl) {
                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    type: method,
                    success: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    },
                    error: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    }
                };
                Ancestor.Dao.ajax(options, authUrl);
            },
            appendAuthUrl: function (options, authUrl) {
                options = $.extend({},options, {
                    beforeSend: function (request) {
                        var authBase = Ancestor.Util.getAuth('/vod/episodeLogList');
                        request.setRequestHeader('Sign', authBase.sign);
                        request.setRequestHeader("Time", authBase.clientTime);
                        request.setRequestHeader("From", authBase.from);
                        request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                    }
                })
                return options;
            },

            sendProxy: function (options, headers) {
                $.ajax(this.transToProxyOptions(options, headers));
            },
            transToProxyOptions: function (options, headers) {
                var requestData = {url: options.url, type: options.type, params: options.data, needCookie: true};
                if (headers != null) {
                    requestData.headers = headers;
                }
                var newOptions = {
                    url: EpgWeb.urlConfig.redirect,
                    type: "post",
                    dataType: "json",
                    timeout: options.timeout?options.timeout: 5000,
                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                    success: function (data) {
                        options.success(data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        options.error(null);
                    }
                }
                return newOptions;
            },
            doGet: function (url, data, callback) {
                var dataArr = [];
                for (var key in data) {
                    dataArr.push(key + "=" + data[key]);
                }

                var options = {
                    url: url,
                    dataType: 'json',
                    data: dataArr.join("&"),
                    type: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                $.ajax(options);
            },
            doAuthData: function (handlerObj) {
                if (auth == null) {
                    auth = Ancestor.Auth;
                }
                auth.getAuthData({tips: 1, url: handlerObj.url}, function (rt) {
                    if (rt == null) {
                        if (handlerObj.hasOwnProperty("doSuccess")) {
                            handlerObj.doSuccess();
                        }
                    } else {
                        if (handlerObj.hasOwnProperty("doError")) {
                            handlerObj.doError();
                        }
                    }
                    if (handlerObj.hasOwnProperty("doFinal")) {
                        handlerObj.doFinal();
                    }
                });
            },
//            checkJSVersion: function (data, callback) {
//                //method, data, callback, authUrl) {
//                this.sendAjax("/api/version/check", "post", {data:JSON.stringify(data)}, callback);
//            }
            notifyAlert: function (sendData, callback) {
                var url = EpgWeb.urlConfig.notifyAlertUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(sendData)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/notify/alertPlatform");
            }

        })
    }
);
define(
    '../epg2/EpgWeb.Task',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Task = (function () {
            var handler = function(data,callback){
                if (callback != null) {
                    callback.call(this, data);
                }
            }
            var getConfigType = function (typeName, callback, regName) {
                if (regName == null) {
                    regName = typeName;
                }
                return {
                    regName: regName,
                    options: {
                        type: "get",
                        url: EpgWeb.urlConfig.configs,
                        dataType: "json",
                        data: {type: typeName},
                        success: function(data){
                            handler.call(this, data,callback);
                        },
                        error: function(data){
                            handler.call(this, data,callback);
                        }
                    }
                }
            }

            var getChannel = function (regName,params) {
                return {
                    regName:regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.channelGet,
                        dataType: "json",
                        data: params
                    }
                }
            }
            return {
                getConfigType: getConfigType,
                getChannel:getChannel
            }
        })()
    }
);
define(
    '../epg2/EpgWeb.PingBack',['require','exports','module'],function (require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };


// [步骤名称 操作结果] [entityId=节目Id][msg=任意消息][stepInfo={json对象，用于携带其它信息}][cost=步骤执行耗时，可选]
        EpgWeb.PingBack = {
            PARAM_TYPE:{
                append_submit:402,
                normal_submit:403
            },
            typeArr: ["create_video", "submit_format"],
            doFoldList: function (originalData) {
                var retValue = originalData;
                try {
                    var newData = JSON.parse(retValue);
                    if (newData.list != null) {
                        newData.list = JSON.parse(newData.list)
                        var newFold = [];
                        var nodeStart = -100;
                        var nodeEnd = -100;
                        var curIndex = 0;
                        $.each(newData.list, function (i, element) {
                            curIndex = element;
                            if (curIndex > nodeEnd + 1) {
                                if (nodeStart >= 0) {
                                    newFold.push({ start: nodeStart, end: nodeEnd});
                                }
                                nodeStart = curIndex;
                                nodeEnd = curIndex;
                            } else if (curIndex == nodeEnd + 1) {
                                nodeEnd = curIndex;
                            }
                        })
                        if (nodeEnd >= nodeStart) {
                            newFold.push({ start: nodeStart, end: nodeEnd});
                        }
                        newData.list = newFold;
                        retValue = JSON.stringify(newData);
                    }
                } catch (e) {
                    console.log("error", e);
                }
                return retValue
            },
            transFormatData: function (wrapData) {
                var ret = {};
                ret.success = wrapData.success;
                if (wrapData.success == true) {
                    ret.successLogExpression = "[" + wrapData.funcType + " success]";
                } else {
                    ret.failLogExpression = "[" + wrapData.funcType + " error]";
                }
                ret.detail = "[entityId=" + wrapData.programId + "][stepInfo=" + this.doFoldList(wrapData.sendData) + "][plusMsg=" + wrapData.plusMsg + "]";
                wrapData.sendData = null;
                ret.keyId = "" + wrapData.programId;
                ret.serverIp = "" + wrapData.serverIp;
                ret.relationData = [
                    {description: "奇谱", columnName: "programId", "columnValue": "" + wrapData.programId, "isQueryParam": "0", "isQueryList": "1"}
                ];
                ret.paramType = wrapData.paramType ?  wrapData.paramType:this.PARAM_TYPE.append_submit;
                return  ret
            },
            doExecute: function (wrapData, callback) {
                var testUrl = "http://xiu-test-monitor-dev001-cqdx.qiyi.virtual/monitor-api/pingback/flow";
                var onlineUrl = "http://monitor.live.qiyi.domain/monitor-api/pingback/flow";
                var paramsArr = [];
                var retData = this.transFormatData(wrapData);
                paramsArr.push({keyName: "business", value: "live2vod"});
                paramsArr.push({keyName: "paramType", value: retData.paramType })
                if (retData.success) {
                    paramsArr.push({keyName: "successLogExpression", value: retData.successLogExpression})
                } else {
                    paramsArr.push({keyName: "failLogExpression", value: retData.failLogExpression})
                }
                paramsArr.push({keyName: "sendTime", value: new Date().getTime() })
                paramsArr.push({keyName: "detail", value: retData.detail});
                paramsArr.push({keyName: "keyId", value: retData.keyId})
                paramsArr.push({keyName: "serverIp", value: retData.serverIp}) //
                paramsArr.push({keyName: "relationData", value: retData.relationData})
                paramsArr.push({keyName: "checkToken", value: md5("business=live2vod|F@(LhCw79plfWd3$83#530")})

                var sendData = {}
                $.each(paramsArr, function (index, element) {
                    if (element.value != null) {
                        sendData[element.keyName] = element.value;
                    }
                })

                for (var key in wrapData) {
                    if(wrapData[key] != null){
                        sendData[key] = wrapData[key];
                    }
                }
                var options = {
                    url: auth.dev() ? testUrl : onlineUrl,
                    dataType: 'json',
                    data: sendData,
                    type: "post",
                    success: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    },
                    error: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    }
                }
                EpgWeb.Dao.sendProxy(options)
            },
            doQuickSend: function (wrapData) {
                this.doExecute(wrapData, function (data) {
                    console.log(data);
                })
            }
        }
    }
);
define(
    '../epg2/EpgWeb.PingBackCost',['require','exports','module'],function (require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };
//        business	业务名称	业务代码：PGC，CPP等	Y	string
//        name	服务名称	该服务名称需要和你在监控中所配置的名称一致	Y	string
//        cost	耗时	单位是毫秒	Y	sring	1000
//        sendTime	投递数据的时间戳	投递数据的时间戳（到秒一级）	Y	string	1493258494
//        detail	透传详细信息	想要传递过来的详细信息，如一条完整日志	N	json string
//        serverIp	机器IP地址	产生投递信息的机器IP	Y	string
//        checkToken	接口签名参数	接口签名参数	Y	string
        EpgWeb.PingBackCost = {
            doExecute: function (wrapData, callback) {
                var testUrl = "http://xiu-test-monitor-dev001-cqdx.qiyi.virtual/monitor-api/pingback/cost";
                var onlineUrl = "http://monitor.live.qiyi.domain/monitor-api/pingback/cost";
                var paramsArr = [];
                var retData = wrapData;
                paramsArr.push({keyName: "business", value: "live2vod"});
                paramsArr.push({keyName: "name", value: "zzd_jqh"});
                paramsArr.push({keyName: "cost", value: retData.costTime + ""});
                paramsArr.push({keyName: "sendTime", value: parseInt(new Date().getTime() / 1000 )  })
                paramsArr.push({keyName: "detail", value: retData.detail});
                paramsArr.push({keyName: "serverIp", value: retData.serverIp}) //
                paramsArr.push({keyName: "checkToken", value: md5("business=live2vod|F@(LhCw79plfWd3$83#530")})

                var sendData = {}
                $.each(paramsArr, function (index, element) {
                    if (element.value != null) {
                        sendData[element.keyName] = element.value;
                    }
                })
                var options = {
                    url: auth.dev() ? testUrl : onlineUrl,
                    dataType: 'json',
                    data: sendData,
                    type: "post",
                    success: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    },
                    error: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    }
                }
                EpgWeb.Dao.sendProxy(options)
            },
            doQuickSend: function (wrapData) {
                this.doExecute(wrapData, function (data) {
                    console.log(data);
                })
            },
            doTest: function (enterData) {
                var demo = $.extend({}, enterData, { costTime: 30000, serverIp: "127.0.0.1", detail: JSON.stringify({msg: "demo"})})
                this.doQuickSend(demo)
            }
        }
    }
);
/**
 * Created by karkarrotxu on 2016/11/8.
 */
define(
    '../vodcom/VODCom',['require','exports','module'],function (require, exports, module) {
        window.VODCom = window.VODCom || {
            version: '1.0'
        };
    }
);
/**
 * Created by karkarrotxu on 2016/11/8.
 */
define(
    '../vodcom/VODCom.EventManager',['require','exports','module'],function (require, exports, module) {
        window.VODCom = window.VODCom || {
            version: '1.0'
        };
        VODCom.EventManager = function () {
            var eventIndex = 0;
            var managerArr = [];
            function bindEvent(eventType, func) {
                eventIndex++;
                var targetObj = {id: eventIndex, type: eventType, handler: function (paramsArray) {
                    func.apply(null, paramsArray)
                }}
                managerArr.push(targetObj);
                return targetObj.id;
            }

            function dispatchEvent(event) {
                $.each(managerArr, function (i, element) {
                    if (element.type == event.type) {
                        element.handler($.isArray(event.data) ? event.data : [event.data]);
                    }
                })
            }

            function removeBind(id) {
                var findTarget = null;
                $.each(managerArr, function (i, element) {
                    if (element.id == id) {
                        findTarget = element;
                    }
                })
                if (findTarget != null) {
                    var index = managerArr.indexOf(findTarget);
                    managerArr.splice(index, 1);
                }
            }

            return{
                bindEvent: bindEvent,
                dispatchEvent: dispatchEvent,
                removeBind: removeBind
            }
        }
    })
;
define(
    '../vodcom/VODCom.Pic',['require','exports','module'],function (require, exports, module) {
        VODCom.Pic = {
            eventManager: VODCom.EventManager(),
            foldStart: -1,
            foldEnd: -1,
            clear: function () {
                this.foldStart = -1;
                this.foldEnd = -1;
                $(".fold_select").removeClass("fold_select");
                console.log("清除收纳信息")
            },
            recordStart: function () {
                if (this.foldStart > 0) {
                    $(".fold_select").removeClass("fold_select");
                }
                this.foldStart = parseInt($(".red").parent().find(".pid").html());
                $(".red").parent().find(".pid").addClass("fold_select");
                if (this.foldEnd < 0) {
                    return;
                }
                this.foldPics(this.foldStart, this.foldEnd);
                $(".fold_select").removeClass("fold_select");
                this.clear();
            },
            recordEnd: function () {
                if (this.foldEnd > 0) {
                    $(".fold_select").removeClass("fold_select");
                }
                this.foldEnd = parseInt($(".red").parent().find(".pid").html());
                $(".red").parent().find(".pid").addClass("fold_select");
                if (this.foldStart < 0) {
                    return;
                }
                this.foldPics(this.foldStart, this.foldEnd);
                $(".fold_select").removeClass("fold_select");
                this.clear();
            },
            //图片收录优化
            foldPics: function (startIndex, endIndex) {
                if (endIndex < startIndex) {
                    var temp = startIndex;
                    startIndex = endIndex;
                    endIndex = temp;
                }
                console.log("图片收录优化")
                var startId = "#img-" + startIndex;
                var endId = "#img-" + endIndex;
                if ($(startId).length > 0 && $(endId).length > 0) {
                    this.eventManager.dispatchEvent({type: "fold_pic", data: [startIndex, endIndex]})
                    for (var imageId = startIndex; imageId <= endIndex; imageId++) {
                        $("#img-" + imageId).parent().hide();
                    }
                    var hiddenArr = $("div[id^=cate]:hidden");
                    var nodeStart = -100;
                    var nodeEnd = -100;
                    var curIndex = 0;
                    var newFold = [];
                    $.each(hiddenArr, function (i, element) {
                        curIndex = parseInt($(element).find("span").html());
                        if (curIndex > nodeEnd + 1) {
                            if (nodeStart >= 0) {
                                newFold.push({ start: nodeStart, end: nodeEnd});
                            }
                            nodeStart = curIndex;
                            nodeEnd = curIndex;
                        } else if (curIndex == nodeEnd + 1) {
                            nodeEnd = curIndex;
                        }
                    })
                    if (nodeEnd >= nodeStart) {
                        newFold.push({ start: nodeStart, end: nodeEnd});
                    }
                    var foldData = $('#makedImg').data("fold");
                    if (foldData == null) {
                        foldData = [];
                    }
                    $.each(foldData, function (i, element) {
                        $("div[fold-key=" + (element.start + "_" + element.end) + "]").remove();
                    })
                    $.each(newFold, function (i, element) {
                        VODCom.Pic.foldDivMakeUp(element);
                    })
                    $('#makedImg').data("fold", newFold);
                }
            },
            foldDivMakeUp: function (element) {
                this.eventManager.dispatchEvent( {type:"fold_makeUp",data:element} )
            },
            extendPics: function (foldSpan) {
                var $foldElement = $(foldSpan).parent();
                var startIndex = parseInt($foldElement.attr("fold-start"));
                var endIndex = parseInt($foldElement.attr("fold-end"));
                var foldData = $('#makedImg').data("fold");
                var newFold = [];
                $.each(foldData, function (i, element) {
                    if (element.start == startIndex && element.end == endIndex) {
                        $foldElement.remove();
                    } else {
                        newFold.push(element);
                    }
                })
                for (var imageId = startIndex; imageId <= endIndex; imageId++) {
                    $("#img-" + imageId).parent().show();
                }
                $('#makedImg').data("fold", newFold);
                this.eventManager.dispatchEvent({type: "extend_pics", data: [startIndex, endIndex]})
            }
        };
        VODCom.Pic.eventManager.bindEvent("change_big_pic",function(){
            $('div[fold-key]').css({
                'width': '280px',
                'height': '220px'
            });
        })
        VODCom.Pic.eventManager.bindEvent("change_small_pic",function(){
            $('div[fold-key]').css({
                'width': '120px',
                'height': '96px'
            });
        })
        VODCom.Pic.eventManager.bindEvent("add_image_mask",function(data){
            console.log("wait to do");
        })
    }
);
define(
    '../vodcom/VODCom.OCR',['require','exports','module'],function (require, exports, module) {
        VODCom.OCR = {
            CH_CHAR: " ０１２３４５６７８９零一二三四五六七八九".split(""),
            EN_CHAR: " 0123456789".split(""),
            //!"',%():
            REMOVE_SIGN:/[！|＇|＂|“|”|‘|’|，|、|％|（|）|。|．|：|"|'|(|)|.|,|!|:|%|　]/g,
                //" !"',%()".split("").join("|"),
            CH_REGEXP_ARR: [],
            CHAR_LENGTH:1,
            NUM_LENGTH:10,
            REGEXP_LENGTH: 11,
            preDealData: function (inputOrigin, ocrOrigin) {
                var retValue = {
                    inputOrigin: inputOrigin,
                    ocrOrigin: ocrOrigin,
                    inputDeal: null,
                    ocrDeal: null,
                    containsOcr: false,
                    inOcr:false
                }
                var inputDeal = inputOrigin;
                var ocrDeal = ocrOrigin;

                for (var i = 0; i < VODCom.OCR.REGEXP_LENGTH; i++) {
                    inputDeal = inputDeal.replace(VODCom.OCR.CH_REGEXP_ARR[i], VODCom.OCR.EN_CHAR[i]);
                    ocrDeal = ocrDeal.replace(VODCom.OCR.CH_REGEXP_ARR[i], VODCom.OCR.EN_CHAR[i]);
                }
                inputDeal = inputDeal.replace(/ /g,"");
                ocrDeal = ocrDeal.replace(/ /g,"");
                retValue.inputDeal = inputDeal;
                retValue.ocrDeal = ocrDeal;
                retValue.containsOcr = ocrDeal.length > 0 && inputDeal.includes(ocrDeal);
                retValue.inOcr = inputDeal.length > 0 && ocrDeal.includes( inputDeal );
                return retValue
            },
            accountOcrPercent: function (ocrOrigin, inputOrigin) {
                var dealData = this.preDealData(ocrOrigin, inputOrigin);
                if (dealData.containsOcr ||  dealData.inOcr) {
                    return 100;
                }
                var ocrTitle = dealData.ocrDeal;
                var userTitle = dealData.inputDeal
                var retValue = this.innerGetMatrix(ocrTitle, userTitle)
                return   parseInt(100 - 100 * retValue / ( ocrTitle.length > userTitle.length ? ocrTitle.length : userTitle.length ));
            },
            innerGetMin: function (one, two, three) {
                var min = one;
                if (two < min) {
                    min = two;
                }
                if (three < min) {
                    min = three;
                }
                return min;
            },
            innerGetMatrix: function (str1, str2) {
                var n = str1.length;
                var m = str2.length;
                if (n == 0) return m;
                if (m == 0) return n;
                var c1, c2, temp;
                var matrix = {};
                var i = 0, j = 0;
                for (i = 0; i <= n; i++) {
                    matrix[i + "_" + 0] = i;
                }
                for (j = 0; j <= m; j++) {
                    matrix[0 + "_" + j] = j;
                }
                for (i = 1; i <= n; i++) {
                    c1 = str1.charAt(i - 1);
                    for (j = 1; j <= m; j++) {
                        c2 = str2.charAt(j - 1);
                        if (c1 == c2) {
                            temp = 0;
                        } else {
                            temp = 1;
                        }
                        matrix[i + "_" + j] = this.innerGetMin(matrix[(i - 1) + "_" + j] + 1, matrix[i + "_" + (j - 1)] + 1, matrix[(i - 1) + "_" + (j - 1)] + temp);
                    }
                }
                return matrix[n + "_" + m];
            }
        };
        VODCom.OCR.CH_REGEXP_ARR.push(VODCom.OCR.REMOVE_SIGN);
        for (var i = 0; i < VODCom.OCR.NUM_LENGTH; i++) {
            VODCom.OCR.CH_REGEXP_ARR.push(new RegExp(VODCom.OCR.CH_CHAR[1+i]+"|"+VODCom.OCR.CH_CHAR[11+i], "g"));
        }
    }
);
define(
    '../vodcom/VODCom.TitleFilter',['require','exports','module'],function (require, exports, module) {
        window.VODCom = window.VODCom || { }
        VODCom.TitleFilter = (function () {
            var replaceArr = [];
            replaceArr.push({rule: new RegExp("伊斯兰国", "g"), value: "IS" });
            function doTitleFilter(original) {
                var ret = original;
                if (ret != null && ret.length > 0) {
                    $.each(replaceArr, function (i, element) {
                        ret = ret.replace(element.rule, element.value);
                    })
                }
                return ret;
            }

            return {
                doTitleFilter: doTitleFilter
            }
        })()
    }
);
define(
    '../vodcom/VODCom.FlashToJS',['require','exports','module'],function (require, exports, module) {
        window.VODCom = window.VODCom || { }
        VODCom.FlashToJS = (function () {
            function notifyJS(eventName, eventData) {
                switch (eventName) {
                    case "cost_time_event":
                        $("body").trigger( eventName ,eventData );
                        break;
                }
            }
            return {
                notifyJS: notifyJS
            }
        })()
    }
);
define(
    '../vodcom/VODCom.H5PlayerControl',['require','exports','module'],function (require, exports, module) {
        window.VODCom = window.VODCom || {};
        window.VODCom.H5PlayerControl = function (options) {
            this.volumeDrag = false;
            this.timeDrag = false;
            this.options = options;
            this.initControl();
        }
        VODCom.H5PlayerControl.prototype.initControl = function(){
            var player = this.options.player;
            var parent = this.options.container;
            var array = this.options.controlDisable|| [];
            $.each(array,function(i,element){
                switch (element){
                    case "progressBar":
                        parent.find(".progress").hide();
                        break;
                    case "timeBar":
                        parent.find(".time").hide();
                        break;
                }
            })
        }
        VODCom.H5PlayerControl.prototype.updateVolume = function (x, vol) {
            var player = this.options.player;
            var parent = this.options.container;
            var volume = parent.find('.volume');
            var percentage;
            if (vol) {
                percentage = vol * 100;
            }
            else {
                var position = x - volume.offset().left;
                percentage = 100 * position / volume.width();
            }
            if (percentage > 100) {
                percentage = 100;
            }
            if (percentage < 0) {
                percentage = 0;
            }
            parent.find('.volumeBar').css('width', percentage + '%');
            player.volume = percentage / 100;

            if (player.volume == 0) {
                parent.find('.sound').removeClass('sound2').addClass('muted');
            }
            else if (player.volume > 0.5) {
                parent.find('.sound').removeClass('muted').addClass('sound2');
            }
            else {
                parent.find('.sound').removeClass('muted').removeClass('sound2');
            }
        }

        VODCom.H5PlayerControl.prototype.playpause = function () {
            var player = this.options.player;
            var parent = this.options.container;
            if (player.paused || player.ended) {
                parent.find('.btnPlay').addClass('paused');
                player.play();
            }
            else {
                parent.find('.btnPlay').removeClass('paused');
                player.pause();
            }
        }

        VODCom.H5PlayerControl.prototype.initVol = function(){
            var player = this.options.player;
            var parent = this.options.container;
            parent.find('.volumeBar').css('width', player.volume * 100 + '%');
        }

        VODCom.H5PlayerControl.prototype.bindEvent = function () {
            var player = this.options.player;
            var parent = this.options.container;
            var self = this;
            parent.hover(function () {
                parent.find('.player_control').stop().animate({'bottom': 0}, 500);
            }, function () {
                if (!self.volumeDrag && !self.timeDrag) {
                    parent.find('.player_control').stop().animate({'bottom': -45}, 500);
                }
            })
            parent.find('.sound').click(function () {
                player.muted = !player.muted;
                $(this).toggleClass('muted');
                if (player.muted) {
                    parent.find('.volumeBar').css('width', 0);
                }
                else {
                    parent.find('.volumeBar').css('width', player.volume * 100 + '%');
                }
            });
            parent.find('.player_control').show().css({'bottom': -45});
            parent.find('.volume').on('mousedown', function (e) {
                self.volumeDrag = true;
                player.muted = false;
                parent.find('.sound').removeClass('muted');
                self.updateVolume(e.pageX);
            });

            parent.find('.btnPlay').on('click', function () {
                self.playpause();
            });
            $(player).bind("click",function(){
                self.playpause();
            })
            $(player).on('ended', function () {
                $('.btnPlay').removeClass('paused');
                player.pause();
            });

            var timeFormat = function(seconds){
                var m = Math.floor(seconds/60)<10 ? "0"+Math.floor(seconds/60) : Math.floor(seconds/60);
                var s = Math.floor(seconds-(m*60))<10 ? "0"+Math.floor(seconds-(m*60)) : Math.floor(seconds-(m*60));
                return m+":"+s;
            };

            $(player).on('timeupdate', function() {
                var currentPos = player.currentTime;
                var maxduration = player.duration;
                var perc = 100 * currentPos / maxduration;
                parent.find('.timeBar').css('width',perc+'%');
                parent.find('.current').text(timeFormat(currentPos));
                $('.duration').text(timeFormat(maxduration));
            });

            $(document).on('mouseup', function (e) {
                if (self.volumeDrag) {
                    self.volumeDrag = false;
                    self.updateVolume(e.pageX);
                }
            });
            $(document).on('mousemove', function (e) {
                if (self.volumeDrag) {
                    self.updateVolume(e.pageX);
                }
            });
        }
    }
);
define(
    '../vodcom/VODCom.H5Player',['require','exports','module'],function (require, exports, module) {
        window.VODCom = window.VODCom || {};
        VODCom.H5Player = (function () {
            var eventManager = VODCom.EventManager();
            var taskOption = null;
            var currentRunningName = null;

            eventManager.bindEvent("do_append", appendSourceHandler);
            var flvManager = {};

            function buildPlayer(playerId, videoId) {
                var videoElement = document.getElementById(videoId);
                if (flvjs.isSupported()) {
                    var flvPlayer = flvjs.createPlayer({
                        "type": "flv",
                        "segments": [
                        ]
                    });
                    flvPlayer.attachMediaElement(videoElement);
                    flvManager[playerId] = {
                        player: flvPlayer,
                        bindEvent: false,
                        video: videoElement,
                        appendMode: false,
                        appendList: [],
                        loadIndex: -1
                    };
                }
            }

            function play(playerId, urlArrayList) {
                stopAppendMode(playerId);
                taskOption.playerId = playerId;
                taskOption.sourceArr = urlArrayList.splice(1);
                taskOption.stop = true;
                taskOption.timerId = setInterval(segmentLoadTrigger, 500);
                var buildConfig = {type: "flv", segments: []};
                $.each(urlArrayList, function (i, element) {
                    buildConfig.segments.push({duration: element.duration, url: element.url })
                })
                var player = flvManager[playerId].player;
                if (player != null) {
                    player.unload();
                    player._mediaDataSource = buildConfig;
                    player.attachMediaElement(flvManager[playerId].video);
                    player._msectl._mediaSource.addEventListener('sourceended', function (event) {
                        taskOption.stop = false;
                        player.currentTime = player.currentTime;
                        console.log("[play]", player.currentTime, taskOption.lastEndTime)
                        if ((player.currentTime == taskOption.lastEndTime) && (player.paused || player.ended)) {
                            flvManager[playerId].control.playpause();
                        } else if (taskOption.shortFlag == true) {
                            console.log("[sourceended]", player.duration, player.currentTime);
                            if (player.duration > 1 || taskOption.sourceArr.length == 0) {
                                taskOption.shortFlag = false;
                                flvManager[playerId].control.playpause();
                            }
                        }
                    });
                    player.load();
                    if (flvManager[playerId].control != null) {
                        if (urlArrayList[0].duration >= 1000) {
                            flvManager[playerId].control.playpause();
                        } else {
                            taskOption.shortFlag = true;
                        }
                    } else {
                        player.play();
                    }
                }
            }

            function singlePlay(playerId, urlArrayList,initStop){
                var buildConfig = {type: "flv", segments: []};
                $.each(urlArrayList, function (i, element) {
                    buildConfig.segments.push({duration: element.duration, url: element.url })
                })
                var player = flvManager[playerId].player;
                if (player != null) {
                    player.unload();
                    player._mediaDataSource = buildConfig;
                    player.attachMediaElement(flvManager[playerId].video);
                }
                player.load();
                if(!initStop){
                    player.play();
                }
            }

            function startAppendMode(playerId, options) {
                stopAppendMode(playerId);
                taskOption.playerId = playerId;
                taskOption.nextIndex = parseInt(options.index) + 1;
                taskOption.maxIndex = parseInt(options.index) + 99999;
                taskOption.stop = true;
                taskOption.timerId = setInterval(queryAppendTrigger, 500);
                var elementData = flvManager[playerId];
                elementData.appendMode = true;
                var buildConfig = {type: "flv", segments: [
                    {url: options.url, duration: options.duration, name: options.name }
                ]};
                $(flvManager[playerId].video).bind("timeupdate", notifyCurrentPlayingImage);
                var player = elementData.player;
                if (player != null) {
                    player.unload();
                    player._mediaDataSource = buildConfig;
                    player.attachMediaElement(flvManager[playerId].video);
                    player._msectl._mediaSource.addEventListener('sourceended', function (event) {
                        taskOption.stop = false;
                        player.currentTime = player.currentTime;
                        console.log("[play]", player.currentTime, taskOption.lastEndTime)
                        if ((player.currentTime == taskOption.lastEndTime) && (player.paused || player.ended)) {
                            flvManager[playerId].control.playpause();
                        } else if (taskOption.shortFlag == true) {
                            console.log("[sourceended]", player.duration, player.currentTime);
                            if (player.duration > 1) {
                                taskOption.shortFlag = false;
                                flvManager[playerId].control.playpause();
                            }
                        }
                    });
                    player.load();
                    if (options.duration >= 1000) {
                        flvManager[playerId].control.playpause();
                    } else {
                        taskOption.shortFlag = true;
                    }
                }
            }

            function segmentLoadTrigger() {
                if (taskOption.stop == true) {
                    return;
                }
                if (taskOption.sourceArr.length == 0) {
                    taskOption.stop = true;
                    return;
                }
                var element = flvManager[taskOption.playerId];
                if (element.video.duration > 60 + element.video.currentTime) {
                    console.log("[segmentLoad]delay load");
                    return;
                }
                var rest = taskOption.sourceArr.splice(taskOption.shortFlag ? 2 : 30);
                var loadArr = taskOption.sourceArr;
                taskOption.sourceArr = rest;
                taskOption.stop = true;
                segmentLoadHandler(flvManager[taskOption.playerId].player, loadArr)
            }

            function queryAppendTrigger() {
                if (taskOption.stop == true) {
                    return;
                }
                if (taskOption.nextIndex >= taskOption.maxIndex) {
                    return;
                }
                var element = flvManager[taskOption.playerId];
                if (element.video.duration > 60 + element.video.currentTime) {
                    console.log("[queryAppendTrigger]delay query");
                    return;
                }
                taskOption.stop = true;
                eventManager.dispatchEvent({type: "need_append_mode", data: {playerId: taskOption.playerId, index: taskOption.nextIndex, quickMode: taskOption.shortFlag }})
            }

            function appendSourceHandler(data) {
                var element = flvManager[ data.playerId];
                if (element != null) {
                    appendSource(element.player, data.resource.list, element)
                }
            }

            function segmentLoadHandler(flvPlayer, loadArr) {
                var hasLength = flvPlayer._mediaDataSource.segments.length;
                var baseTime = flvPlayer.currentTime * 1000;
                var start = hasLength
                $.each(loadArr, function (i, element) {
                    flvPlayer._mediaDataSource.segments.push({duration: element.duration, url: element.url, timestampBase: baseTime, cors: true, withCredentials: false});
                    baseTime += element.duration;
                    hasLength++;
                })
                taskOption.lastEndTime = flvPlayer.duration;
                flvPlayer._transmuxer._controller._loadSegment(start);
            }

            function appendSource(flvPlayer, resourceArr, manager) {
                if (resourceArr.length == 0) {
                    return;
                }
                var hasLength = flvPlayer._mediaDataSource.segments.length;
                var baseTime = flvPlayer.duration * 1000;
                var start = hasLength
                var segments = [];
                $.each(resourceArr, function (i, element) {
                    segments.push($.extend({}, { duration:element.length,name:element.name,url:element.url }, {timestampBase: baseTime, cors: true, withCredentials: false}));
                    baseTime += element.length;
                    hasLength++;
                })

                $.each(segments, function (i, element) {
                    flvPlayer._mediaDataSource.segments.push(element)
                })
                console.log(" start ")
                taskOption.nextIndex = parseInt(resourceArr[resourceArr.length - 1].name) + 1;
                taskOption.lastEndTime = flvPlayer.duration;

                flvPlayer._transmuxer._controller._loadSegment(start);
            }

            function stopAppendMode(playerId) {
                if (flvManager[playerId].appendMode == true) {
                    flvManager[playerId].appendMode = false;
                }
                if(currentRunningName != null){
                    currentRunningName = null;
                    eventManager.dispatchEvent({ type:"change_running_img", data: {name: null }})
                }
                $(flvManager[playerId].video).unbind("timeupdate", notifyCurrentPlayingImage);
                initTaskOption();
            }

            function notifyCurrentPlayingImage(event) {
                var player = flvManager["flash"].player;
                var currentTime = player.currentTime * 1000;
                var tempArr = [].concat(player._mediaDataSource.segments);
                var currentName = null;
                $.each(tempArr, function (i, element) {
                    if (element.duration + element.timestampBase > currentTime) {
                        currentName = element.name;
                        return false;
                    }
                })
                if (currentName == null) {
                    currentRunningName = null;
                    eventManager.dispatchEvent({ type:"change_running_img", data: {name: null }})
                } else if (currentRunningName != currentName) {
                    currentRunningName = currentName;
                    eventManager.dispatchEvent({ type:"change_running_img", data: {name: currentName }});
                }
            }

            function initTaskOption() {
                if (taskOption != null) {
                    if (taskOption.timerId > 0) {
                        clearInterval(taskOption.timerId);
                        taskOption.timerId = -1;
                    }
                    taskOption.playerId = null;
                }
                taskOption = {
                    timerId: -1,
                    playerId: null,
                    stop: true,
                    nextIndex: -1,
                    maxIndex: -1,
                    shortFlag: false
                };
            }

            function bindControl(playerId) {
                var control = new VODCom.H5PlayerControl({
                    player: flvManager[playerId].video,
                        controlDisable:["progressBar","timeBar"],
                    container: $(flvManager[playerId].video).parent()

                })
                control.bindEvent();
                control.initVol();
                flvManager[playerId].control = control;
            }

            function getPlayerData(playerId) {
                return flvManager[playerId];
            }

            return {
                buildPlayer: buildPlayer,
                bindControl: bindControl,
                play: play,
                eventManager: eventManager,
                startAppendMode: startAppendMode,
                getPlayerData: getPlayerData,
                singlePlay:singlePlay
            }
        })()
    }
);
define(
    '../vodcom/VODCom.AutoTitle',['require','exports','module'],function (require, exports, module) {
        VODCom.AutoTitle = {
            AUTO_TITLE_QUERY_FLAG: 0,
            AUTO_TITLE_FLAG: 0,
            AUTO_TITLE_ORIGIN: null,
            USER_TITLE_SELECT: -1,
            parentInstance: null,
            contentInstance: null,
            lastQueryKey: null,
            dataCenter: [],
            CropInstance: null,
            options: null,
            stopQuery: false,
            clearData: function () {
                this.AUTO_TITLE_QUERY_FLAG = 0;
                this.AUTO_TITLE_FLAG = 0;
                this.AUTO_TITLE_ORIGIN = null;
                $("div.hint_title").remove();
                this.dataCenter = [];
                this.lastQueryKey = null;
            },
            initAutoTitleDlg: function (options) {
                var self = this;
                self.options = options;
                self.getParentDiv().dialog({
                    title: "标题自动识别",
                    resizable: false,
                    dialogClass: 'alert',
                    autoOpen: false,
                    width: 820,
                    modal: true,
                    open: function () {
                        if ($("label[name=label_sel_auto_title]").length > 0) {
                            if ($("label.title_selected").length == 0) {
                                $("label[name=label_sel_auto_title]:eq(0)").click();
                            }
                        }
                    },
                    close: function () {
                        console.log(" 标题自动识别 关闭");
                        $("#auto_title_alterDiv").hide();
                        self.options["body"].append($("#auto_title_alterDiv"));

                    }
                })
                self.CropInstance = $.Jcrop("#auto_image", {
                    onChange: self.doCropChange,
                    onSelect: self.doCropSelect,
                    boxHeight: 450,
                    minSelect: [10, 10]
                })

                $("button[name=auto_title-ok]").on("click", function (event) {
                    self.getParentDiv().dialog("close");
                    if (self.getContentDiv().find("input[type=radio]:checked").length > 0) {
                        var selTitle = self.getContentDiv().find("input[type=radio]:checked").parent().next().text()
                        $("input[name=videoName]").val(selTitle.trim());
                        $("input[name=videoName]").change();
                        self.AUTO_TITLE_QUERY_FLAG = 1;
                        self.AUTO_TITLE_FLAG = 1;
                        self.AUTO_TITLE_ORIGIN = self.dataCenter[  parseInt(self.getContentDiv().find("input[type=radio]:checked").val()) - 1].key.trim();
                        self.getOptionsEntity("config").OCR_TITLE_FLAG = 0;
                    }
                })
                $("button[name=auto_title-cancel]").on("click", function (event) {
                    self.AUTO_TITLE_QUERY_FLAG = 0;
                    self.getParentDiv().dialog("close");
                })
            },

            getParentDiv: function () {
                if (this.parentInstance == null) {
                    this.parentInstance = $("#auto_title-dlg");
                }
                return this.parentInstance
            },
            getContentDiv: function () {
                if (this.contentInstance == null) {
                    this.contentInstance = $("#auto_title-dlg_content");
                }
                return this.contentInstance
            },
            bindEvent: function () {
                var self = this;
                $("button[name=btn_get_auto_title]").bind("click", function (event) {
                    self.getAutoTitleList();
                })
                self.getContentDiv().delegate("label[name=label_sel_auto_title]", "click", function (event) {
                    $(event.currentTarget).parent().find("input[name=auto_selected_title]").click();
                })
                var alterDiv = $("#auto_title_alterDiv");
                self.getContentDiv().delegate("input[name=auto_selected_title]", "click", function (event) {
                    var brother = $(event.currentTarget).parent().next();
                    alterDiv.find("input[name=image_auto_title]").val(brother.text());
                    alterDiv.find("input[name=image_auto_title]").change();
                    alterDiv.show();
                    brother.parent().append(alterDiv);
                    self.loadDataImage(parseInt($(event.currentTarget).val()) - 1);
                })

                alterDiv.find("input[name=image_auto_title]").bind("blur", function (event) {
                    alterDiv.hide();
                    var newValue = alterDiv.find("input[name=image_auto_title]").val();
                    if (newValue.trim().length > 0) {
                        alterDiv.parent().find("label[name=label_sel_auto_title]").text(newValue);
                    }
                })
            },

            buildTitleLabel: function (elementText, elementId, deepIndex) {
                var labelElement = $('<div class="datarow" ><label><input type="radio" name="auto_selected_title" value="' + deepIndex + '" />标题' + deepIndex + '：</label><label name="label_sel_auto_title" bindImage="' + elementId + '"  style="">' + elementText + '</label></div>')
                return labelElement;
            },

            getOptionsEntity: function (key) {
                var self = this;
                return self.options[key];
            },

            getAutoTitleList: function () {
                var self = this;
                var settings = self.getOptionsEntity("settings");
                var tips = self.getOptionsEntity("tips");
                var validate = self.getOptionsEntity("validate");
                var dao = self.getOptionsEntity("dao");
                var config = self.getOptionsEntity("config");

                if (settings.taskid < 0) {
                    tips("error", "参数错误！");
                    return
                }
                var sTime = $.trim($('input[name=sTime]').val()) ,
                    eTime = $.trim($('input[name=eTime]').val());
                if (!validate.checkNum(sTime) || !validate.checkNum(eTime) || settings.taskid < 1) {
                    tips("error", "请填写起点和终点！");
                    return;
                }
                eTime = parseInt(eTime);
                sTime = parseInt(sTime);
                if (eTime <= sTime) {
                    tips("error", "起点应该小于终点！");
                    return;
                }
                if (eTime >= parseInt($("#picNum").text())) {
                    tips("error", "终点尚未加载，请稍后");
                    return;
                }
                var sendData = { start: sTime, end: eTime, from_client: true, key: settings.taskid };
                var newQueryKey = sendData.start + "_" + sendData.end;
                if (self.lastQueryKey == newQueryKey) {
                    self.initContentDiv();

                    return;
                }

                self.dataCenter = [];
                dao.getAutoTitleList(sendData, function (rdata) {
                    if (rdata != null && rdata.code == "A00000") {
                        self.lastQueryKey = newQueryKey;
                        self.getContentDiv().html("");
                        if (rdata.title == null || rdata.title.length < 3) {
                            tips("", "目标区域无可识别标题");
                        } else {
                            var afterDeal = rdata.title.replace(/u('\S+')/g, "$1").replace(/"/g, "\\\"").replace(/'/g, "\"").replace(/\\x([0-9a-f]{2})/g, "\\u00$1")
                            console.log("afterDeal:" + afterDeal);
                            afterDeal = VODCom.TitleFilter.doTitleFilter(afterDeal);
                            var jsonArr = JSON.parse(afterDeal);
                            var tempArr = [];
                            var filterArr = [];

                            var bindDataCenter = [];
                            var index = -1;

                            $.each(jsonArr, function (idx, element) {
                                element.transRange = [];
                                if (element.range != null && element.range.length >= 1) {
                                    element.transRange.push({st: element.range[0], et: element.range[element.range.length - 1] })
                                }
                                index = tempArr.indexOf(element.text)
                                if (index == -1) {
                                    index = tempArr.push(element.text) - 1;
                                    bindDataCenter[index] = { first: element.id, key: element.text, refer: [element], range: [].concat(element.transRange) };
                                    filterArr.push(bindDataCenter[index]);
                                    bindDataCenter[index].deepIndex = filterArr.length;
                                } else {
                                    bindDataCenter[index].refer.push(element);
                                    bindDataCenter[index].range = bindDataCenter[index].range.concat(element.transRange);
                                }
                            })
                            if (filterArr.length > 0) {
                                self.dataCenter = filterArr;
                                self.initContentDiv();
                            }

                        }

                    }
                })
            },
//            saveModifyText: function () {
//                var self = this;
//                var rowArr = self.getContentDiv().find("div.datarow");
//                $.each(rowArr, function (i, elemt) {
//                    self.dataCenter[i].modifyText = $(elemt).find("label[name=label_sel_auto_title]").text()
//                })
//            },
            initContentDiv: function () {
                var self = this;
                self.getContentDiv().html("");
                var stopLength = 5;
                var tips = self.getOptionsEntity("tips");
                if (self.dataCenter.length == 0) {
                    tips("", "目标区域无可识别标题");
                } else {
                    $.each(self.dataCenter.slice(0, stopLength), function (idx, element) {
                        self.buildTitleLabel(element.key, element.first, element.deepIndex).appendTo(self.getContentDiv());
                    });
                    self.getParentDiv().dialog("open");
                }
            },
            doPostEpgAutoTitleData: function (baseObj) {
                var self = this;
                var dao = self.getOptionsEntity("dao");
                var tips = self.getOptionsEntity("tips");

                if (self.AUTO_TITLE_QUERY_FLAG == 1) {
                    var sendData = self.prepareAutoTitleData(baseObj);
                    dao.postAutoTitleData({data: JSON.stringify(sendData) }, function (data) {
                        if (data != null && data.code == "A00000") {
                            tips("success", '投递epg 自动识别标题 数据成功');
                        } else {
                            tips("error", '投递epg 自动识别标题 数据失败');
                        }
                    });
                }
            },
            prepareAutoTitleData: function (baseObj) {
                var self = this;
                var util = self.getOptionsEntity("util");
                var config = self.getOptionsEntity("config");
                var data = {
                    channelName: baseObj.channelName,
                    autoTitle: $.trim(self.AUTO_TITLE_ORIGIN),
                    autoTitleCharLen: 0,
                    addTime: util.formatDateTimeFormat(new Date()),
                    liveBeginTime: baseObj.begin,
                    liveEndTime: baseObj.end,
                    autoFlag: self.AUTO_TITLE_FLAG,
                    user: util.getUserName(),
                    userTitle: $.trim(baseObj.title),
                    userTitleCharLen: 0,
                    legoProgramId: baseObj.programId,
                    percent: 0,
                    titleError: 0,
                    autoTitleStart: -1,
                    autoTitleEnd: -1,
                    userTitleSelect: -1
                };
                data.autoTitleCharLen = Com.string.getStrLength(data.autoTitle);
                data.userTitleCharLen = Com.string.getStrLength(baseObj.title);
                data.percent = VODCom.OCR.accountOcrPercent(data.autoTitle, data.userTitle);
                if (config.OCR_TITLE_FLAG == 1) {
                    data.userTitleSelect = self.USER_TITLE_SELECT;
                    if (!this.checkInRange(data.userTitleSelect)) {
                        data.titleError = 1
                    }
                }
                return data;
            },

            checkInRange: function (userTitleSelect) {
                var checkOver = false;
                var inRange = false;
                $.each(this.dataCenter, function (i, element) {
                    $.each(element.range, function (j, elem) {
                        if (elem.st <= userTitleSelect && userTitleSelect <= elem.et) {
                            checkOver = true;
                            inRange = true;
                            return false;
                        }
                    })
                    if (checkOver) {
                        return false;
                    }
                })
                console.log("userTitleSelect: " + userTitleSelect + ( inRange ? " is " : "isn't" ) + "  in range");
                return inRange
            },

            doCropChange: function (obj) {

            },
            doCropSelect: function (obj) {
                var self = this;
                console.log("doCropSelect " + JSON.stringify(obj));
                if (VODCom.AutoTitle.stopQuery == true) {
                    return;
                }

                var scale = 1;
                var showObj = {
                    x: parseInt(obj.x / scale),
                    y: parseInt(obj.y / scale),
                    w: Math.ceil(obj.w / scale),
                    h: Math.ceil(obj.h / scale)
                };
                console.log("doCropSelect " + JSON.stringify(obj) + "," + JSON.stringify(showObj))
                $("input[name=image_location]").val(JSON.stringify(showObj));
                VODCom.AutoTitle.reqOcrResult(showObj);
            },
            loadDataImage: function (dataIndex) {
                var self = this;
                var data = self.dataCenter[dataIndex].refer[0];
                var imgUrl = data.imagepath;
                var rect = data.rect;
                $("#auto_image_load_text").html("图片加载中....");
                $("#auto_image_load_text_div").show();
                $("#auto_image_load_text_div").hide();
                $("#auto_image").unbind();
                $("#auto_image").bind("load", function (event) {
                    console.log(" auto_image load complete");
                    var newRect = [ rect.x, rect.y , rect.w, rect.h];
                    self.stopQuery = true;
                    self.CropInstance.setSelect([newRect[0], newRect[1], newRect[0] + newRect[2], newRect[1] + newRect[3]  ]);
                    self.stopQuery = false;
                })
                $("#auto_image").attr("src", imgUrl);
                self.CropInstance.setImage(imgUrl);
                console.log("  doMarkOcrImage suc");
            },

            reqOcrResult: function (obj) {
                var self = this;
                var dao = self.getOptionsEntity("dao");
                var tips = self.getOptionsEntity("tips");
                var paramsData = dao.getParamsData();
                var imageName = $("#auto_image").attr("src").split("/").pop()
                var data = {
                    image_name: imageName,
                    channel_code: paramsData.channel_name,
                    from_client: true,
                    key: dao.settings.taskid,
                    x: obj.x,
                    y: obj.y,
                    w: obj.w,
                    h: obj.h
                };
                dao.getOcrResult2(data, function (rData) {
                    console.log("getOcrResult2:" + rData == null ? "" : JSON.stringify(rData));
                    if (rData != null && rData.code == "A00000") {
                        rData.result = rData.result.trim();
                        var alterDiv = $("#auto_title_alterDiv");
                        alterDiv.find("input[name=image_auto_title]").val(rData.result);
                        alterDiv.find("input[name=image_auto_title]").change();
                        if (rData.result.length > 0) {
                            alterDiv.parent().find("label[name=label_sel_auto_title]").text(rData.result);
                        }
                    } else {
                        tips("error", "识别标题失败!");
                    }
                })
            }
        };
    }
);
define(
    '../vodcom/VODCom.Player',['require','exports','module'],function (require, exports, module) {
        VODCom.Player = (function () {
            var playOnePosition = {
                left: '',
                top: ''
            }
            var flashvars = {};
            var textArr = [];
            var params = {};
            params.scale = "noscale";
            params.salign = "tl";
            params.wmode = "transparent";
            params.swliveconnect = "true";
            params.allowfullscreen = "true";
            params.allowscriptaccess = "always";
            params.allownetworking = "all";
            params.bgcolor = "#000000";
            var player = {};
            player.swf = "http://www.iqiyi.com/player/20130702143439/expressInstall.swf";
            player.version = "10.0.0";
            player.ScreenPrintUrl = "/epg/swfs/ScreenPrint.swf?20156291103";
            var settings = null;
            var _configOptions = null;
            var _accurateFrame = null;
            var _dao = null;
            var _tips = null;
            // 左侧播放器
            function initLeftPlayer() {
                VODCom.H5Player.buildPlayer("flash", "ppsLiveDiv");
                VODCom.H5Player.bindControl("flash");
                VODCom.H5Player.eventManager.bindEvent("need_append_mode", queryResource);
                VODCom.H5Player.eventManager.bindEvent("change_running_img", changeRunningImg);
            }

            function initViewImagePlayer() {
                VODCom.H5Player.buildPlayer("flashImage", "viewImageVideo");
            }

            // 单张图片视频预览播放器
            function initPicPlayer() {
                VODCom.H5Player.buildPlayer("flashOne", "ppsLiveOneFrame");
            }

// 起止帧精确化播放器
            function initFramePlayer() {
                var _attributes = {};
                _attributes.id = "accurateStartEndFrame";
                _attributes.pause = "暂停";
                params.scale = "Showall";
                if (checkFlash()) {
                    swfobject.embedSWF(player.ScreenPrintUrl, "accurateStartEndDiv", "100%", "100%", player.version, player.swf, flashvars, params, _attributes);
                } else {
                    noFlashTip("accurateStartEndDiv");
                }
            }

            //搭建js与flash互通的环境
            function thisMovie(movieName) {
                if (navigator.appName.indexOf("Microsoft") != -1) {
                    return window[movieName];
                } else {
                    return document[movieName];
                }
            }

            function playAll(allList, mode) {
                textArr = [];
                doViewImage(false);
                VODCom.H5Player.play("flash", allList.list)
            }

            function playOne(allList) {
                textArr = [];
                $.each(allList.list, function (i, element) {
                    textArr.push({url: element.url});
                })
                $("#play-one").css({
                    top: playOnePosition.top,
                    left: playOnePosition.left
                });
                $("#play-one").show();
                VODCom.H5Player.singlePlay('flashOne', textArr)
            }

            function initPlayStop(allList) {
                textArr = [];
                $.each(allList.list, function (i, element) {
                    textArr.push({url: element.url});
                })
                VODCom.H5Player.singlePlay('flashImage', textArr, true)
                if (VODCom.H5Player.getPlayerData("flash").video.paused) {
                    doViewImage(true);
                }
            }

            function doViewImage(show) {
                if (show) {
                    $("#video_preview_image_div").show();
                    $("#ppsLiveDiv").hide();
                    $("div.player_control").hide();
                } else {
                    $("#video_preview_image_div").hide();
                    $("#ppsLiveDiv").show();
                    $("div.player_control").show();
                }
            }

            function updatePosition(options) {
                playOnePosition.left = options.left;
                playOnePosition.top = options.top;
            }

            function initPlayer(configOptions) {
                _configOptions = configOptions
                _accurateFrame = getConfigEntity("accurateFrame");
                _dao = getConfigEntity("dao");
                settings = _dao.settings;
                _tips = getConfigEntity("tips");
                initLeftPlayer();
                initViewImagePlayer();
                initPicPlayer();
                initFramePlayer();
                registerCostTimeEvent();
            }

            function getConfigEntity(entityKey) {
                return _configOptions[entityKey];
            }

            function registerCostTimeEvent() {
                console.log("[Player]registerCostTimeEvent ");

                $("body").on("cost_time_event", function (event, data) {
                    EpgWeb.PingBackCost.doQuickSend({serverIp: _dao.getParamsData().ip, costTime: data.costTime + "", detail: {msg: data.isOverTime ? "time out" : "suc" }  })
                    if (data.isOverTime == true) {
                        SystemDialog.queryConfirm("图片请求失败，请退出重新加载", function (flag) {
                            _accurateFrame.accurateStartEndRemove();
                            if (flag) {
                                _accurateFrame.doLastHandlerQ();
                            }
                        }, {"btn_ok": "重新请求", "btn_cancel": "退出请求" });
                    }
                })
            }

            function queryResource(data) {
                var listUrl = _dao.getDotData().listUrl;
                $.get(listUrl, {
                    'key': _dao.settings.taskid,
                    'from_client': true,
                    'index': data.index,
                    'type': 0,
                    'offset': data.quickMode ? 2 : 30
                }, function (rdata) {
                    VODCom.H5Player.eventManager.dispatchEvent({type: "do_append", data: {playerId: data.playerId, resource: rdata }})
                }, 'json');
            }

            function changeRunningImg(data) {
                $("div img.fragment-img").css({backgroundColor: "transparent"})
                if (data.name != null) {
                    $("#img-" + data.name).css({backgroundColor: "green"})
                }
            }

            //播放功能
            function liveView(viewTime, options) {
                var duration = getFormatDuration(options.duration);
                doViewImage(false);
                VODCom.H5Player.startAppendMode("flash", {index: viewTime, url: options.url, duration: duration, name: options.name});
                //    var video VODCom.H5Player.getPlayerData("flash").video;
                //从刘志红那里取json列表
                //传给王鹏
            }

            //播放1帧
            function viewOne(viewTime) {
                //从刘志红那里取json列表
                var listUrl = _dao.getDotData().listUrl;
                $.get(listUrl, {
                    'key': _dao.settings.taskid,
                    'from_client': true,
                    'index': viewTime,
                    'type': 0,
                    'offset': 1
                }, function (data) {
                    playOne(data);
                }, 'json');
                //传给王鹏
            }

            //播放1帧
            function viewStopImage(viewTime) {
                var listUrl = _dao.getDotData().listUrl;
                $.get(listUrl, {
                    'key': _dao.settings.taskid,
                    'from_client': true,
                    'index': viewTime,
                    'type': 0,
                    'offset': 1
                }, function (data) {
                    initPlayStop(data);
                }, 'json');

            }

            function splitData(stime, etime, needRemoveDelData) {
                stime = parseInt(stime);
                etime = parseInt(etime);

                settings.subData = [];
                var needDatas = [];
                for (i = stime; i <= etime; i++) {
                    needDatas.push(i);
                }
                //console.log(needDatas);
                //console.log(delList);
                if (needRemoveDelData && settings.delList.length) {
                    $.each(settings.delList, function (k, v) {
                        v = parseInt(v);
                        if (stime <= v && v <= etime) {
                            for (var i = 0; i < needDatas.length; i++) { //删除v的元素
                                if (needDatas[i] == v) {
                                    needDatas.splice(i, 1);
                                    break;
                                }
                            }
                        }
                    })
                }
                settings.subData = needDatas;
                //console.log(subData);
            }

            function review() {
                if (!settings.subData.length) {
                    //alert('请先打点,再预览!');
                    _tips("error", '请先打点,再预览!');
                    return false;
                }
                var reviewData = {
                    'list': []
                };
                //console.log(subData);
                $.each(settings.subData, function (k, v) {
                    var src = $('#img-' + v).attr('src');
                    if (!src) {
                        //alert('数据为空不能预览!');
                        return false;
                    }
                    var duration = getFormatDuration($('#img-' + v).attr('duration'))
                    reviewData.list.push({url: src.replace(/jpg/g, "flv"), name: k + "", duration: duration  });
                })

                playAll(reviewData);
            }

            //打好的点预览
            var reviewOne = function (s, e, vType) {
                var reviewOneData = {
                    'list': []
                };
                s = parseInt(s);
                e = parseInt(e);
                var src , flv, obj, duration;
                for (var i = s; i <= e; i++) {
                    if (settings.delList.length && vType != "删除") {
                        var isNeed = true;
                        for (var j = 0; j <= settings.delList.length; j++) {
                            var v = settings.delList[j];
                            if (i == v) {
                                isNeed = false;
                            }
                        }
                        if (isNeed) {
                            src = $('#img-' + i).attr('src');
                            duration = getFormatDuration($('#img-' + v).attr('duration'))
                            obj = {url: src.replace(/jpg/g, "flv"), name: i + "", duration: duration }

                            reviewOneData.list.push(obj);
                        }
                    } else {
                        src = $('#img-' + i).attr('src');
                        duration = getFormatDuration($('#img-' + v).attr('duration'))
                        obj = {url: src.replace(/jpg/g, "flv"), name: i + "", duration: duration }
                        reviewOneData.list.push(obj);
                    }
                }
                //console.log(reviewOneData);
                playAll(reviewOneData);
            }

            function nofind(img_url) {
                var img = event.srcElement;
                img.src = img_url;
            }

            function checkFlash() {
                var flag = false;
                if (window.ActiveXObject) {
                    try {
                        var swf = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
                        if (swf) {
                            flag = true;
                        }
                    } catch (e) {
                    }
                } else {
                    try {
                        var swf = navigator.plugins['Shockwave Flash'];
                        if (swf) {
                            flag = true;
                        }
                    } catch (e) {
                    }
                }

                if (flag) {
                    console.log("flash running ok");
                } else {
                    console.log("flash running error");
                }

                return flag;
            }

            function noFlashTip(elementId) {
                var e = $("#" + elementId);
                if (!e) {
                    return;
                }
                e.html('<div class="position:absolute;top:50%;left:50%;z-index:99;margin-left:-165px;margin-top:-60px;padding:35px32px;width:266px;background:#eaedef;border-radius:5px;color:#333;"><p>您没有安装Flash播放器或者Flash播放器版本过低</p><p>请点击<a href="http://get.adobe.com/cn/flashplayer/">这里</a>安装</p><p class="grey">安装完毕之后请刷新页面或者重新启动浏览器</p></div>')
            }


            function getFormatDuration(duration) {
                if (duration == null || duration == "") {
                    return 2000;
                }
                return parseInt(duration);
            }

            function changePlayPause(playerId) {
                VODCom.H5Player.getPlayerData(playerId).control.playpause();
                if (!VODCom.H5Player.getPlayerData(playerId).video.paused) {
                    doViewImage(false);
                }
            }

            return {
                initPlayer: initPlayer,
                playAll: playAll,
                playOne: playOne,
                updatePosition: updatePosition,
                viewOne: viewOne,
                viewStopImage: viewStopImage,
                view: liveView,
                nofind: nofind,
                splitData: splitData,
                review: review,
                reviewOne: reviewOne,
                checkFlash: checkFlash,
                changePlayPause: changePlayPause,
                doViewImage: doViewImage
            }
        })()
    }
);
define(
    '../vodcom/VODCom.NewsHighlight',['require','exports','module'],function (require, exports, module) {
        VODCom.NewsHighlight = (function () {
            var _config = null;
            var lastOption = null;
            var defaults = {
                st: 0,
                et: 0,
                pic: 0,
                color: 'cfff',
                bgColor: 'c09f',
                removeColor: ''
            };

            function setHighLight(options) {
                quickClearBgColor();
                $('.p-l').remove();
                $('.p-r').remove();
                $('.p-middle').remove();
                reSetOpacity();
                if (options != null) {
                    lastOption = $.extend({}, defaults, options);
                    addBackgroundColor(lastOption)
                    addInOutMark(lastOption);
                } else {
                    lastOption = null;
                }
            }

            function addInOutMark(options) {
                var bigMark = '';
                if ($("#changeBigPic").hasClass('btn-primary')) {
                    bigMark = 'in-out-mark-b';
                }
                var showIdTitle = options.id == -999 ? " " : options.id;
                var str = "";
                if (options.hasOwnProperty("st")) {
                    str = '<div onclick="VODCom.NewsHighlight.clearPoint(this,1)" class="absolute in-out-mark-s ' + bigMark + ' p-l p-l-' + options.id + '">' + showIdTitle + '<br>入<br>点</div>';
                    $('#img-' + options.st).after(str);
                    $('#img-' + options.st).parent().find(".p-r").remove();
                }
                if (options.hasOwnProperty("et")) {
                    str = '<div onclick="VODCom.NewsHighlight.clearPoint(this,2)" class="absolute in-out-mark-s ' + bigMark + ' p-r p-r-' + options.id + '">' + showIdTitle + '<br>出<br>点</div>';
                    $('#img-' + options.et).after(str);

                    $('#img-' + options.et).parent().find(".p-l").remove();
                }
                VODCom.NewsHighlight.reSetOpacity();
                if (options.hasOwnProperty("pic")) {
                    str = '<div onclick="$(this).remove()" class="absolute in-out-mark-s ' + bigMark + ' p-middle p-middle-' + options.id + '">' + showIdTitle + '<br>封<br>面</div>';
                    $('#img-' + options.pic).after(str);
                }
            }

            function addInOutMaskMark(options) {
                var bigMark = '';
                if ($("#changeBigPic").hasClass('btn-primary')) {
                    bigMark = 'in-out-mark-b';
                }
                var showIdTitle = options.maskIndex < 0 ? " " : options.maskIndex;
                var str = "";
                if (options.hasOwnProperty("maskST")) {
                    $('#img-' + options.maskST).parent().find(".mask-r").remove();
                }
                if (options.hasOwnProperty("maskET")) {
                    $('#img-' + options.maskET).parent().find(".mask-l").remove();
                }
                if (options.hasOwnProperty("maskST")) {
                    str = '<div onclick="$(this).remove()" class="absolute in-out-mark-s ' + bigMark + ' mask-l mask-l-' + options.maskIndex + '">' + showIdTitle + '<br>遮<br>头</div>';
                    $('#img-' + options.maskST).after(str);
                }

                if (options.hasOwnProperty("maskET")) {
                    str = '<div onclick="$(this).remove()" class="absolute in-out-mark-s ' + bigMark + ' mask-r mask-r-' + options.maskIndex + '">' + showIdTitle + '<br>遮<br>尾</div>';
                    $('#img-' + options.maskET).after(str);
                }
            }

            function setMaskStart(value) {
                var entity = _config.MaskManager.getSelectMaskEntity();
                if (entity == null) {
                    _config.Plugin.tips("error", _config.Config.REMIND_MSG_INFO.NOT_BIND_MASK);
                    return;
                }
                var newstart = value == null ? validCheck() : value;
                $('.mask-l-' + entity.index).remove();
                addInOutMaskMark({maskST: newstart, maskIndex: entity.index, maskET: entity.eTime});
                _config.Util.updateGridMaskEntityRow({index: entity.index, sTime: newstart, eTime: entity.eTime  })
            }

            function setMaskEnd(value) {
                var entity = _config.MaskManager.getSelectMaskEntity();
                if (entity == null) {
                    _config.Plugin.tips("error", _config.Config.REMIND_MSG_INFO.NOT_BIND_MASK);
                    return;
                }
                var newEnd = value == null ? validCheck() : value;
                $('.mask-r-' + entity.index).remove();
                addInOutMaskMark({maskET: newEnd, maskIndex: entity.index, maskST: entity.sTime});
                _config.Util.updateGridMaskEntityRow({index: entity.index, eTime: newEnd, sTime: entity.sTime  })
            }

            function clearMaskMark() {
                $('.mask-l').remove();
                $('.mask-r').remove();
            }

            function clearMaskSingleMark(index) {
                $('.mask-l-' + index).remove();
                $('.mask-r-' + index).remove();
            }

            function addBackgroundColor(options) {
                for (var i = options.st; i <= options.et; i++) {
                    if (!options.removeColor) {
                        $('#img-' + i).addClass(options.color).addClass(options.bgColor);
                    } else {
                        $('#img-' + i).removeClass(options.color).removeClass(options.bgColor);
                    }
                }
            }

            function quickClearBgColor() {
                $('.c09f').removeClass("c09f");
                $('.cfff').removeClass("cfff");
            }

            function validCheck() {
                return parseInt($(".red").parent().find(".pid").html());
            }

            function setNewStart(value) {
                quickClearBgColor();
                var newstart = value == null ? validCheck() : value;
                var maxValue = parseInt($('#picNum').text()) - 1;
                if (newstart != null) {
                    if (newstart >= maxValue) {
                        console.log("wrong  st " + newstart)
                        return;
                    }
                    var updateObj = {id: -999, sTime: newstart};
                    _config.AccurateFrame.updateAccurateFrame({head: '', headSetted: false})
                    _config.Util.updateCForm(updateObj)
                    $('.p-l').remove();
                    addInOutMark({ id: -999, st: newstart})
                }
            }

            function setNewEnd(value) {
                quickClearBgColor();
                var newEnd = value == null ? validCheck() : value;
                if (newEnd != null) {
                    if (newEnd == 0) {
                        console.log("wrong et " + newEnd);
                        return;
                    }
                    var updateObj = {id: -999, eTime: newEnd};
                    _config.AccurateFrame.updateAccurateFrame({end: '', endSetted: false})
                    _config.Util.updateCForm(updateObj)
                    $('.p-r').remove();
                    addInOutMark({ id: -999, et: newEnd})
                }
            }


            function setNewImage(value) {
                quickClearBgColor();
                var image = value == null ? validCheck() : value;
                if (image != null) {
                    var updateObj = { id: -999, pic: image};
                    _config.Util.updateCForm(updateObj);
                    $('.p-middle').remove();
                    addInOutMark({ id: -999, pic: image})
                }
            }

            function getLastOption() {
                if (lastOption == null) {
                    return null;
                }
                return $.extend({}, lastOption);
            }

            function setNewOption(options) {
                switch (options.key) {
                    case "st":
                        setNewStart(options.value);
                        break;
                    case "et":
                        setNewEnd(options.value);
                        break;
                    case "pic":
                        setNewImage(options.value)
                        break;
                }
            }

            function clearPoint(element) {
                $(element).remove();
                reSetOpacity();
            }

            function reSetOpacity() {
//                $("img.fragment-img").parent().css({
//                    opacity: 1
//                })
//                var st = $(".p-l").parent().find(".pid").text();
//                var et = $(".p-r").parent().find(".pid").text();
//                if (st == "" && et == "") {
//                    return;
//                } else {
//                    if (st != "") {
//                        $("img.fragment-img:lt(" + st + ")").parent().css({
//                            opacity: 0.3
//                        })
//                    }
//                    if (et != "") {
//                        $("img.fragment-img:gt(" + et + ")").parent().css({
//                            opacity: 0.3
//                        })
//                    }
//                }
            }

            function triggerAddNewImage() {
//                var et = $(".p-r").parent().find(".pid").text();
//                if (et != "") {
//                    $("img.fragment-img:gt(" + et + ")").parent().css({
//                        opacity: 0.3
//                    })
//                }
            }

            function bindConfig(newConfig){
                _config = newConfig;
            }

            return {
                bindConfig:bindConfig,
                setHighLight: setHighLight,
                setNewStart: setNewStart,
                setNewEnd: setNewEnd,
                setNewImage: setNewImage,
                getLastOption: getLastOption,
                setNewOption: setNewOption,
                quickClearBgColor: quickClearBgColor,
                addInOutMaskMark: addInOutMaskMark,
                setMaskStart: setMaskStart,
                setMaskEnd: setMaskEnd,
                clearMaskMark: clearMaskMark,
                clearMaskSingleMark: clearMaskSingleMark,
                clearPoint: clearPoint,
                reSetOpacity: reSetOpacity,
                triggerAddNewImage: triggerAddNewImage
            }

        })()
    }
);
/**
 * Created by karkarrotxu on 2016/11/8.
 */
define(
    '../vodnew/VODNew',['require','exports','module'],function (require, exports, module) {
        window.VODNew = window.VODNew || {
            version: '1.0',
            g_i: 0,
            g_mi: 0
        };
        VODNew.Constant = {
            baseApiUrl: "/api/",
            baseModeApiUrl_test: "http://10.23.70.33:7007/",
            baseModeApiUrl_produce: "http://dot.live.qiyi.domain/",
            //    thirdUrl_peditor_submit:"http://lego.iqiyi.com/peditor/submit",
            thirdUrl_simple_video: 'http://lego.iqiyi.com/suggest/simple-video',
            thirdUrl_channel: 'http://lego.iqiyi.com/suggest/operation', // 频道
            thirdUrl_album: 'http://lego.iqiyi.com/suggest/album',
            thirdUrl_peditor_submit: 'http://lego.iqiyi.com/peditor/submit', // 提交节目信息给lego
            //cpUrl : 'http://lego.iqiyi.com/live2VOD/cp/search', // 合作方接口
         //   thirdUrl_cpUrl: 'http://dispatch.live2vod.qiyi.domain/v1/partner/find',  //合作方接口 线上
            thirdUrl_cpUrl: 'http://dot.live.qiyi.domain/v1/partner/find',  //合作方接口 线上
            thirdUrl_test_cpUrl: 'http://10.23.70.33:7004/v1/partner/find',  //合作方接口 线上
            thirdUrl_locationUrl: 'http://lego.iqiyi.com/suggest/location-type',  //地区suggest接口

            //灰度上线地址
            devMode: auth.dev()
        }

        VODNew.urlConfig = (function () {
            var useUrl = VODNew.Constant.baseApiUrl;
            var redirectUrl = useUrl + "redirect";
            var modifyUrl = ( auth.dev() ? VODNew.Constant.baseModeApiUrl_test : VODNew.Constant.baseModeApiUrl_produce ) + "v1/ablum/modify";
            var partnerUrl = auth.dev() ? VODNew.Constant.thirdUrl_test_cpUrl : VODNew.Constant.thirdUrl_cpUrl;
            var submitLogUrl = useUrl + "vod/saveLog";
            var submitEpisodeLogUrl = useUrl + "vod/saveEpisodeLog";
            var submitOcr2DataUrl = useUrl + "statistic/ocr/new";
            var submitAutoTitleDataUrl = useUrl + "statistic/auto/new";
            return {
                modifyUrl: modifyUrl,
                redirect: redirectUrl,
                partnerUrl: partnerUrl,
                submitLogUrl: submitLogUrl,
                submitOcr2DataUrl: submitOcr2DataUrl,
                submitEpisodeLogUrl: submitEpisodeLogUrl,
                submitAutoTitleDataUrl:submitAutoTitleDataUrl
            }
        })()
    }
);
define(
    '../vodnew/VODNew.Action',['require','exports','module'],function (require, exports, module) {
        VODNew.Action = (function () {

            var editMergeForm = null;

            function initWindowEvent() {
                window.onbeforeunload = function () {
                    var warning = "确认要重新打点吗？";
                    return warning;
                }
                $(window).unbind("keydown").bind("keydown", function (e) {
                    return  VODNew.Evt.globalEvent(e);
                });
                window.onresize = function () {
                    VODNew.Util.browserZoomTips();
                    VODNew.Util.LayoutInit();
                    //  VODNew.Util.doNewsGridResize();
                };
            }

            var editMergeRun = function () {
                var mainFunc = function(){
                    if (editMergeForm == null) {
                        editMergeForm = new VODNew.EditMerge($.extend(true, {
                            $FrameGrid: $('#frame_list'),
                            $AdvertGrid: $('#advert_list'),
                            $NewsGrid: $('#news_list'),
                            $NewsSubmitGrid: $('#auto_submit_list'),
                            $NewsDelGrid: $('#auto_del_list'),
                            $MaskGrid: $('#mask_list')
                            //     $FragmentGrid:$('#fragment_list')
                            // '$form': $('form[role=form]')
                        }, {}));
                        setTimeout(function () {
                            $("body footer").hide();
                            console.log("隐藏footer");
                        }, 2000)
                        editMergeForm.init();
                        initWindowEvent();
                    }
                }

                mainFunc();

//                EpgWeb.Dao.checkJSVersion([{name: "VODNew"}], function (data) {
//                    var versionCheck = false;
//                    if (data != null && data.code == "A00000") {
//                        versionCheck = data.version == VODNew.version;
//                    }
//                    if (versionCheck) {
//                        mainFunc();
//                    } else {
//                        SystemDialog.queryConfirm("页面过时，请重新刷新!", function (flag) {
//                            window.location.reload(true)
//                        });
//                    }
//                })
            }
            return {
                editMergeRun: editMergeRun
            }
        })();
    }
);
///import js-src/lib/
///import js-src/com/
define('../vodnew/VODNew.Config',['require','exports','module'],function (require, exports, module) {
    VODNew.Config = $.extend({}, {}, {
        BIG_PIC_MODE: 'style="width:264px;height:204px"',
        SMALL_PIC_MODE: 'style="width:104px;height:64px"',
        Global: {
            picWH: 'style="width:104px;height:64px"',
            smallPic: true,
            isClicked: false,
            error: '',
            channelInfo: [],
            sty2Data: {},
            d_sty2Data: [], // 广告头和尾
            noneDataNum: 0,
            fp_pos: 0,
            statisticOcrTitle: ""
        },

        HELP_DATA: [
            ["点击 + F 键", "打入点帧"],
            ["点击 + D 键", "打出点帧"],
            ["点击 + S 键", "打视频封面"],
            ["点击 + A 键", "提交打点"],
            ["点击 + V 键", "打删除(广告)的开始帧"],
            ["点击 + C 键", "打删除(广告)的结束帧"],
            ["点击 + Z 键", "提交删除"],
            ["点击 + Q 键", "出点、入点精确化裁剪"],
            ["点击 + W 键", "时间片预览"],
            ["点击 + R 键", "标题OCR识别"],
            ["点击 + [ 键", "遮罩起点"],
            ["点击 + ] 键", "遮罩终点"],
            ["点击 + \\ 键", "添加遮罩区域"],
            ["ALT + Q 键", "添加遮标信息"],
            ["X 键", "拆条列表"],
            ["E 键", "智能辅助拆条"],
            ["点击 + T 键", "分片终点"],
            ["Y 键", "提交分片"],
            ["点击 + N 键", "图片收纳结束"],
            ["点击 + M 键", "图片收纳开始"],
            ["B 键", "清除收纳标记"],
            ["上、下、左、右方向键", "上、下、左、右切换"]
        ],
        HELP_DATA_AUTO_TITLE:[
            ["G 键", "标题自动识别"]
        ],
        HELP2_DATA: [
            ["点击 + F 键", "打入点"],
            ["点击 + D 键", "打出点"],
            ["点击 + S 键", "打视频封面"],
            ["点击 + Q 键", "入点、出点、封面精确化裁剪"],
            ["点击 + W 键", "时间片预览"],
            ["X 键", "拆条列表"],
            ["上、下、左、右方向键", "上、下、左、右切换"]
        ],
        ZOOM_HINT: {
            BIG: '您当前浏览器处于放大状态,按<strong>ctrl+0</strong>使用体验更佳!',
            SMALL: '您当前浏览器处于缩小状态,按<strong>ctrl+0</strong>使用体验更佳!'
        },
        PGC: 0,
        UGC: 1,
        adLibHead: 0, // 片头
        adLibTail: 1, // 片尾
        adLib: 2,// 广告

        RED_LAYOUT: '<div class="layout transparent red" onClick="this.remove();">&nbsp;</div>',
//["index", "inpoint", "outpoint", "title","channel","album","cover", "status", "operate"]
        TABLE_COLMODEL_CONFIG: {
            index: {
                name: "index",
                index: 'index',
                title: false,
                width: 45,
                sortable: false,
                align: "center"
            },
            inpoint: {
                name: "sTime",
                index: 'sTime',
                title: false,
                width: 70,
                sortable: false,
                align: "center"
            },
            outpoint: {
                name: "eTime",
                index: 'eTime',
                title: false,
                width: 70,
                sortable: false,
                align: "center"
            },
            ad_inpoint: {
                name: "sTime",
                index: 'sTime',
                title: false,
                width: 70,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return   VODNew.Util.formatter.ad_inpoint(v, o, r);
                }
            },
            ad_outpoint: {
                name: "eTime",
                index: 'eTime',
                title: false,
                width: 70,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return   VODNew.Util.formatter.ad_outpoint(v, o, r);
                }
            },
            title: {
                name: "title",
                index: 'title',
                title: false,
                width: 180,
                sortable: false
            },
            title_news_submit: {
                name: "title",
                index: 'title',
                title: false,
                width: 205,
                sortable: false,
                formatter: function (v, o, r) {
                    return   VODNew.Util.formatter.title_news_submit(v, o, r);
                }
            },
            title_news_del: {
                name: "title",
                index: 'title',
                title: false,
                width: 255,
                sortable: false,
                formatter: function (v, o, r) {
                    return   VODNew.Util.formatter.title_news_del(v, o, r);
                }
            },
            news_title: {
                name: "title",
                index: 'title',
                title: false,
                width: 165,
                sortable: false,
                formatter: function (v, o, r) {
                    return   VODNew.Util.formatter.news_title(v, o, r);
                }
            },
            channel: {
                name: "channel",
                index: 'channel',
                title: false,
                width: 60,
                sortable: false,
                align: "center"
            },
            album: {
                name: "album",
                index: 'album',
                title: false,
                width: 60,
                sortable: false,
                align: "center"
            },
            cover: {
                name: "pic",
                index: 'pic',
                title: false,
                width: 70,
                sortable: false,
                align: "center"
            },
            status: {
                title: false,
                width: 80,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return   "已生成";
                }
            },
            operate_frame: {
                index: 'operate',
                title: false,
                width: 160,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return  VODNew.Util.formatter.operate_frame(v, o, r);
                }
            },
            operate_advert: {
                index: 'operate',
                title: false,
                width: 160,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return VODNew.Util.formatter.operate_advert(v, o, r);
                }
            },

            operate_news_merge: {
                index: 'operate',
                title: false,
                width: 97,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return VODNew.Util.formatter.operate_news_merge(v, o, r);
                }
            },
            operate_merge_submit: {
                index: 'operate',
                title: false,
                width: 57,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return VODNew.Util.formatter.operate_merge_submit(v, o, r);
                }
            },
            operate_merge_del: {
                index: 'operate',
                title: false,
                width: 100,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return VODNew.Util.formatter.operate_merge_del(v, o, r);
                }
            },

            error_hint: {
                title: false,
                width: 70,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return VODNew.Util.formatter.error_hint(v, o, r);
                }
            },
            news_id: {
                name: "regId",
                index: 'regId',
                title: false,
                width: 40,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return VODNew.Util.formatter.news_id(v, o, r);
                }

            },
            hidden_news_id: {
                name: "hidden_news_id",
                title: false,
                sortable: false,
                hidden: true,
                align: "center",
                formatter: function (v, o, r) {
                    return VODNew.Util.formatter.hidden_news_id(v, o, r);
                }
            },

            inpoint2: {
                name: "sTime",
                index: 'sTime',
                title: false,
                width: 45,
                sortable: false,
                align: "center"
            },
            outpoint2: {
                name: "eTime",
                index: 'eTime',
                title: false,
                width: 45,
                sortable: false,
                align: "center"
            },
            cover2: {
                name: "pic",
                index: 'pic',
                title: false,
                width: 45,
                sortable: false,
                align: "center"
            },
            operate_mask: {
                index: 'operate',
                title: false,
                width: 100,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return VODNew.Util.formatter.operate_mask(v, o, r);
                }
            }
        },
        TABLE_ADVERT_LIST: {
            multiselect: false,
            datatype: "local",
            height: 300,
            caption: "广告列表",
            colNames: ["序号" , "入点", "出点", "标题 ", "状态", "操作"  ],
            colModel: ["index", "ad_inpoint", "ad_outpoint", "title", "status", "operate_advert"],
            rowNum: 10,
            pager: "#advert_pager",
            onPaging: function (pgButton) {
                var retValue = VODNew.Util.pageBeanPageHandler("advert_list", "advert_pager", VODNew.Config.PageBeanAdvert, pgButton);
                if (retValue != null) {
                    $("#advert_list")[0].addJSONData(retValue)
                }
                return "stop";
            }
        },
        TABLE_FRAME_LIST: {
            multiselect: false,
            datatype: "local",
            height: 300,
            rowNum: 10,
            caption: "拆条列表",
            colNames: ["序号" , "入点", "出点", "标题 ", "频道", "专辑", "封面", "状态", "操作" ],
            colModel: ["index", "inpoint", "outpoint", "title", "channel", "album", "cover", "status", "operate_frame"],
            pager: "#frame_pager",
            onPaging: function (pgButton) {
                var retValue = VODNew.Util.pageBeanPageHandler("frame_list", "frame_pager", VODNew.Config.PageBeanFrame, pgButton);
                if (retValue != null) {
                    $("#frame_list")[0].addJSONData(retValue)
                }
                return "stop";
            }
        },
        TABLE_MERGE_SUBMIT_LIST: {
            multiselect: false,
            datatype: "local",
            height: 300,
            rowNum: 10,
            caption: "已提交列表",
            colNames: ["序号" , "标题 ", "入点", "出点", "封面", "频道", "专辑", "状态", "操作" ],
            colModel: ["index", "title_news_submit", "inpoint", "outpoint", "cover", "channel", "album", "status", "operate_merge_submit"],
            pager: "#auto_submit_pager",
            onPaging: function (pgButton) {
                var retValue = VODNew.Util.pageBeanPageHandler("auto_submit_list", "auto_submit_pager", VODNew.Config.PageBeanNewsSubmit, pgButton);
                if (retValue != null) {
                    $("#auto_submit_list")[0].addJSONData(retValue)
                }
                return "stop";
            }
        },
        TABLE_MERGE_DEL_LIST: {
            multiselect: false,
            datatype: "local",
            height: 300,
            rowNum: 10,
            caption: "已删除列表",
            colNames: ["序号" , "标题 ", "入点", "出点", "封面", "操作" ],
            colModel: ["index", "title_news_del", "inpoint", "outpoint", "cover", "operate_merge_del"],
            pager: "#auto_del_pager",
            onPaging: function (pgButton) {
                var retValue = VODNew.Util.pageBeanPageHandler("auto_del_list", "auto_del_pager", VODNew.Config.PageBeanNewsDel, pgButton);
                if (retValue != null) {
                    $("#auto_del_list")[0].addJSONData(retValue)
                }
                return "stop";
            }
        },

        TABLE_MASK_LIST: {
            multiselect: false,
            datatype: "local",
            height: 300,
            width: 450,
            rowNum: 10,
            caption: "遮标信息录入",
            colNames: ["序号" , "入点", "出点", "操作" ],
            colModel: ["index", "inpoint", "outpoint", "operate_mask"],
            pager: "#mask_pager",
            toolbar: [true, "top"],
            onPaging: function (pgButton) {
                var retValue = VODNew.Util.pageBeanPageHandler("mask_list", "mask_pager", VODNew.Config.PageBeanMaskEntity, pgButton);
                if (retValue != null) {
                    $("#mask_list")[0].addJSONData(retValue)
                }
                return "stop";
            },
            beforeSelectRow: function (rowid, e) {
                var selIndex = parseInt(rowid)
                var describedby = $(e.target).attr("aria-describedby");
                if (describedby != null) {
                    var cellKey = describedby.replace("mask_list_", "");
                    switch (cellKey) {
                        case "sTime":
                        case "eTime":
                            var rowData = VODNew.Config.PageBeanMaskEntity.findData("index", selIndex);
                            var gotoAim = parseInt($(e.target).html());
                            VODNew.Util.setMaskHighLight(null);
                            if (gotoAim >= 0) {
                                VODNew.Util.setMaskHighLight(rowData);
                                VODNew.Util.fromLIstJump(gotoAim);
                            }
                            return true;
                    }
                }
                var rowData = VODNew.Config.PageBeanMaskEntity.findData("index", selIndex);
                if (rowData.sTime >= 0) {
                    VODNew.Util.setMaskHighLight(rowData);
                    VODNew.Util.fromLIstJump(rowData.sTime);
                }
                return true;
            },
            localReader: {
                id: "index",
                root: "rows",
                page: "page",
                total: "total",
                records: "records"
            }
        },
        TABLE_NEWS_LIST2: {
            multiselect: false,
            datatype: "local",
            height: 350,
            toolbar: [true, "top"],
            caption: "新闻智能辅助拆条列表",
            colNames: ["序号", "标题" , "入点", "出点", "封面 ", "操作", "隐藏主键"],
            colModel: ["news_id", "news_title", "inpoint2", "outpoint2", "cover2", "operate_news_merge", "hidden_news_id"],
            pager: "#news_pager",
//            multiselect: true,
            rowNum: 100,
            onPaging: function (pgButton) {
                var retValue = VODNew.Util.pageBeanPageHandler("news_list", "news_pager", VODNew.Config.PageBeanNews, pgButton);
                if (retValue != null) {
                    $("#news_list")[0].addJSONData(retValue)
                }
                return "stop";
            },
            beforeSelectRow: function (rowid, e) {
                var describedby = $(e.target).attr("aria-describedby");
                if (describedby != null) {
                    var cellKey = describedby.replace("news_list_", "");
                    switch (cellKey) {
                        case "checked":
                            return false;
                        case "pic":
                        case "sTime":
                        case "eTime":
                            var rowData = VODNew.Config.PageBeanNews.findData("regId", rowid);
                            VODNew.Util.setHighLight(rowData);
                            VODNew.Util.fromLIstJump(parseInt($(e.target).html()));
                            return true;
                        case "myTitle":
                            break;
                    }
                }
                var rowData = VODNew.Config.PageBeanNews.findData("regId", rowid);
                VODNew.Util.setHighLight(rowData);
                VODNew.Util.fromLIstJump(rowData.sTime);
                if (e.target.tagName == "A") {
                    $("#news_list").jqGrid('setSelection', rowid);
                }
                return true;
            },
            localReader: {
                id: "regId",
                root: "rows",
                page: "page",
                total: "total",
                records: "records"
            }
        },


        INFO_COMPLETE_WAIT_DO: "拆条完成，还有N条未审核",
        INFO_UN_COMPLETE: "正在拆条，还有N条未审核",
        INFO_COMPLETE: "等待开播",
        PageBeanFrame: null,
        PageBeanAdvert: null,
        PageBeanNewsSubmit: null,
        PageBeanNewsDel: null,
        PageBeanMaskEntity: null,
        PageBeanNews: null,
        PageBeanTemp: null,
        CropInstance: null,
        INIT_SUCCESS: false,
        EDIT_MODE_TYPE: 1,// 1:拆条参数,2:新闻发布
        LAST_SUBMIT_TIME: "",
        DOT_SUBMIT_TIME: "",
        FIRST_FRAGMENT_START: null,
        SORT_RULE: {
            asc_news_regId: function (a, b) {
                return a.regId > b.regId ? 1 : -1
            },
            asc_news_sTime: function (a, b) {
                return a.sTime > b.sTime ? 1 : -1
            },
            desc_news_index: function (a, b) {
                return a.index > b.index ? -1 : 1
            }
        },
        // 资讯25、财经24、军事28、娱乐7
        FORCE_CHECK_IMAGE: {
            tag7: "娱乐",
            tag25: "资讯",
            tag24: "财经",
            tag28: "军事"
        },
        OCR_RESULT_CALL: false,
        OCR_TITLE_FLAG: 0,
        OCR_TITLE_ORIGIN: null,


        VOD_LOG_TYPE: {
            addElement: 101,
            delElement: 102,
            modifyElement: 103,
            includeElement: 104,
            stopElement: 105,
            sendProgramDataToLego: 106,
            submitDotData: 107,
            submitFragmentData: 108,
            submitOcrTitleData: 115,
            getImageData: 117,
            addAdvertAccurate: 118,
            delAdvertAccurate: 119
            //   submitAutoTitleData:120
        },
        ALERT_PLATFORM_NOTIFY: {
            SEND_CHAT: 1,
            SEND_MAIL: 2,
            SEND_MSG: 4
        },

        KEY_CODE: {
            A: 65,
            B: 66,
            C: 67,
            D: 68,
            E: 69,
            F: 70,
            G: 71,
            ESC: 27,
            Q: 81,
            R: 82,
            S: 83,
            T: 84,
            V: 86,
            W: 87,
            X: 88,
            Y: 89,
            Z: 90,
            ZERO: 48,
            LEFT: 37,
            UP: 38,
            RIGHT: 39,
            DOWN: 40,
            M: 77,
            N: 78,
            LEFT_SQUARE_BRACKET: 219,
            BACKSLASH: 220,
            RIGHT_SQUARE_BRACKET: 221,
            SPACE:32
        },
        originalImageSize: {
            width: 0,
            height: 0,
            limitHeight: 603,
            limitWidth: 1072,
            newWidth: 0,
            newHeight: 0,
            scale: 1
        },
        fragmentPid: 0,
        LAST_FRAGMENT_REMIND_TIME: 0,
        LAST_FRAGMENT_REMIND_ENABLE: false,
        HeartBeat: null,
        fgRemindObj: null,
        lastSubmitObj: {programId: -1, hasSubmit: false},
        lastLegoSubmitObj: {programId: -1, hasSubmit: false},
        AUTO_SUBMIT_TRIGGER: false,
        REMIND_MSG_INFO: {
            NORMAL: "确认删除么?",
            FRAGMENT_SUBMIT: "请确保当前分片中的广告已经提交，否则将影响视频生产!",
            ADVERT_SUBMIT: "当前的输入的广告范围在已提交的分片之中，提交后已经影响到后台生产，之后请注意在提交分片前去除广告。",
            ADVERT_DEL: "您想删除的广告范围在已提交的分片之中，删除后已经影响到后台生产，之后提交广告请注意准确性。",
            ADVERT_CROSS: "与已提交的广告点有交叉,请修改!",
            NOT_BIND_MASK: '尚未关联遮标!',
            GET_IMG_FAIL:"获取图片数据失败"
        },
        ALERT_USER: {
            TEST_SEND: "yangzhenkun,karkarrotxu",
            PRO_SEND: "yangzhenkun,liuyankui"
        },
        CODE_SUC: "A00000",
        ADVERT_SUPPORT: false,
        WHITE_LIST_ONLINE: [
//            {ip: "10.13.17.29", cn: "北京卫视高清"},
//            {ip: "10.13.17.28", cn: "北京新闻高清"},
//            {ip: "10.13.17.27", cn: "北京科教"}
            {ip: "10.121.202.13", cn: "北京卫视高清"}
        ],
        WHITE_LIST_DEV: [
            {ip: "10.23.70.35",cn:"北京新闻"},
			{ip: "10.6.5.124",cn:"CCTV13"},
            {ip: "10.6.5.125",cn:"北京卫视高清"}
        ],
        READ_IMAGE_METHOD:"new"
    });
    VODNew.Config.GREY_MODE = {
        inRange:false,
        containsObj: function (obj) {
            var inRange = true;
            VODNew.Config.GREY_MODE.inRange = true;
//            obj = $.extend({}, {ip: "", cn: ""}, obj);
//            var checkArr = VODNew.Config.WHITE_LIST_ONLINE;
//            if (auth.dev()) {
//                checkArr = VODNew.Config.WHITE_LIST_DEV
//            }
//
//            $.each(checkArr, function (i, element) {
//                if(obj.ip == element.ip && obj.cn == element.cn ){
//                    inRange = true;
//                    VODNew.Config.GREY_MODE.inRange = true;
//                    return false;
//                }
//            })
            return inRange;
        },

        MASK_TEST: null
    }
});
define('../vodnew/VODNew.Util',['require','exports','module'],function (require, exports, module) {
    VODNew.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            operate_frame: function (cellvalue, options, rowObject) {
                return '<button type="button" class="btn btn-info" onclick="VODNew.Util.delFrame(' + rowObject.index + ')">删除</button>' +
                    '<button  type="button" class="btn" onclick="VODCom.Player.reviewOne(\'' + rowObject.sTime + '\',\'' + rowObject.eTime + '\',\'打点\');">预览</button>' +
                    '<button type="button" class="btn" onclick="VODNew.Util.fromLIstJump(' + rowObject.sTime + ');" >跳转</button>';
            },
            operate_advert: function (cellvalue, options, rowObject) {
                return '<button type="button" class="btn btn-info" onclick="VODNew.Util.delAdvert(' + rowObject.index + ')">删除</button>' +
                    '<button  type="button" class="btn" onclick="VODCom.Player.reviewOne(\'' + rowObject.sTime + '\',\'' + rowObject.eTime + '\',\'删除\');">预览</button>' +
                    '<button type="button" class="btn" onclick="VODNew.Util.fromLIstJump(' + rowObject.sTime + ');" >跳转</button>';
            },
            operate_mask: function (cellvalue, options, rowObject) {
                return  '<button type="button" class="btn btn-info" onclick="VODNew.MaskManager.modifyMaskEntity(' + rowObject.index + ')">修改</button>' +
                    '<button type="button" class="btn btn-info" onclick="VODNew.MaskManager.delMaskEntity(' + rowObject.index + ')">删除</button>';
            },
            news_title: function (cellvalue, options, rowObject) {
                if (cellvalue.length == 0) {
                    return "";
                }
                if (VODNew.Config.PageBeanNews == null) {
                    return "";
                }
                var findData = VODNew.Config.PageBeanNews.findData("regId", parseInt(rowObject.regId));
                if (findData.showTitle == null) {
                    var titleArr = JSON.parse(cellvalue);
                    if (titleArr.length == 0) {
                        findData.showTitle = "";
                    } else {
                        findData.showTitle = titleArr[0];
                    }
                }
                return '<div style="min-height: 20px;min-width: 100px" aria-describedby="myTitle">' + findData.showTitle + '</div><a style="text-underline-position: below;color:blue" onclick="VODNew.Util.AlterTitle(' + rowObject.regId + ' )">选择</a>'
            },
            title_news_del: function (cellvalue, options, rowObject) {
                var findData = VODNew.Config.PageBeanNewsDel.findData("regId", parseInt(rowObject.regId));
                return findData.showTitle;
            },
            title_news_submit: function (cellvalue, options, rowObject) {
                //      var findData = VODNew.Config.PageBeanNewsSubmit.findData("regId", parseInt(rowObject.regId));
                return cellvalue;
            },

            operate_news_merge: function (cellvalue, options, rowObject) {
                var ret = '<a style="cursor: pointer;color:blue;" onclick="VODNew.Util.viewNews(' + rowObject.regId + ')">预览</a>|' +
                    '<a style="cursor: pointer;color:blue" onclick="VODNew.Util.fillFormNews(' + rowObject.regId + ' )">导入</a>|' +
                    '<a style="cursor: pointer;color:blue" onclick="VODNew.Util.mockDelNews(' + rowObject.regId + ' )">删除</a>'
                if (rowObject.isMergeMode) {
                    ret += '|<br><a style="cursor: pointer;color:blue" onclick="VODNew.Util.undoMerge(' + rowObject.regId + ' )">撤销合并</a>';
                }
                return ret;
            },
            operate_merge_submit: function (cellvalue, options, rowObject) {
                var ret = '<a style="cursor: pointer;color:blue" onclick="VODCom.Player.reviewOne(' + rowObject.sTime + ',' + rowObject.eTime + ',\'打点\' )">预览</a>';
                return ret;
            },
            operate_merge_del: function (cellvalue, options, rowObject) {
                var ret = '<a style="cursor: pointer;color:blue" onclick="VODNew.Util.viewNewsDel(' + rowObject.regId + ' )">预览</a>|' +
                    '<a style="cursor: pointer;color:blue" onclick="VODNew.Util.cancelMergeDel(' + rowObject.regId + ' )">撤销删除</a>';
                return ret;
            },

            error_hint: function (cellvalue, options, rowObject) {
                return "";
            },
            news_id: function (cellvalue, options, rowObject) {
                var ret = "";
                ret = "<input type='checkbox' onclick='VODNew.Util.doRowSelected(this)' aria-describedby='checked'  value='@val' @checked  >".replace("@checked", (rowObject.checked ? "checked" : "")).replace("@val", cellvalue) + cellvalue
                return ret;
            },
            hidden_news_id: function (cellvalue, options, rowObject) {
                return rowObject.regId;
            },
            ad_inpoint: function (cellvalue, options, rowObject) {
                return  rowObject.sTime + ( rowObject.head != "" ? "(" + rowObject.head + " )" : "");
            },
            ad_outpoint: function (cellvalue, options, rowObject) {
                return  rowObject.eTime + ( rowObject.end != "" ? "(" + rowObject.end + " )" : "");
            }
        },

        getUrlParams: function () {
            // var queryStringArr = location.search.match(new RegExp("[\?\&][^\?\&]+=[^\?\&]+", "g")),
            var queryStringArr = decodeURIComponent(location.search).substring(1).split("&"),
                queryStringObj = {}
            var itemArr = [];
            try {
                if (queryStringArr != null) {
                    for (var i = 0; i < queryStringArr.length; i++) {
                        itemArr = queryStringArr[i].split("=");
                        if (i == 0) {
                            queryStringObj['channel_code'] = itemArr[0];
                            queryStringObj['ip'] = itemArr[1];
                        }
                        else {
                            queryStringObj[itemArr[0]] = itemArr[1];
                        }
                    }
                }
            }
            catch (e) {
                console.log("URL地址参数有误，请确认！")
                //  VODNew.Plugin.tips("error","URL地址参数有误，请确认！");
            }
            return queryStringObj;
        },
        LayoutInit: function () {
            $(".tab-content").css({
                height: VODNew.Util.getPageRelativeMesurement().height - 300 - 10 - 49 - 20 - 2
            });
            $("#makedImg").css({
                height: VODNew.Util.getPageRelativeMesurement().height - 90 - 2
            });
        },
        getUserAgent: function () {
            var ua = navigator.userAgent;

            var result = {
                isStrict: document.compatMode == "CSS1Compat",
                isGecko: /gecko/i.test(ua) && !/like gecko/i.test(ua),
                isWebkit: /webkit/i.test(ua)
            };

            try {
                if (/(\d+\.\d+)/.test(external.max_version)) {
                    result.maxthon = +RegExp['\x241'];
                }
            } catch (e) {
                console.log(e);
            }

            if (/msie (\d+\.\d+)/i.test(ua)) {
                result.ie = document.documentMode || +RegExp['\x241'];
            } else if (/trident(\.*?)/i.test(ua)) {
                result.ie = document.documentMode || +RegExp['\x241'];
            } else if (/chrome\/(\d+\.\d+)/i.test(ua)) {
                result.chrome = +RegExp['\x241'];
            } else if (/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(ua) && !/chrome/i.test(ua)) {
                result.safari = +(RegExp['\x241'] || RegExp['\x242']);
            } else if (/firefox\/(\d+\.\d+)/i.test(ua)) {
                result.firefox = +RegExp['\x241'];
            } else if (/opera(?:\/| )(\d+(?:\.\d+)?)(.+?(version\/(\d+(?:\.\d+)?)))?/i.test(ua)) {
                result.opera = +(RegExp["\x244"] || RegExp["\x241"]);
            }

            return result;
        },
        detectBrowserSupport: function (browser) {
            var support = false;
            if (browser.isWebkit || browser.firefox) {
                support = true;
            }
            if (browser.ie && browser.ie >= 9) {
                support = true;
            }
            if (!support) {
                var str = '警告！您使用的浏览器版本过低，为了获得更好使用体验。请使用Chrome、Firefox或IE10浏览器。谢谢！';
                VODNew.Plugin.tips("error", str);
            }

        },

        // 加载合作方信息
        setCooperativePartner: function (categoryName) {
            var self = this;
            $('#cp').html("");
            var videoTypeMinusOne = self.isVideoType1();
            if (videoTypeMinusOne) {
                return;
            }
            var channel_name = VODNew.Dao.getParamsData().channel_name;
            // 关联合作方信息
            VODNew.Dao.getCooperativePartner({
                'channeltype': categoryName,
                'channelalias': channel_name,
                'ptype': 'UGC',
                'pageNo': 0,
                'pageSize': 1000
            }, function (cps) {
                if (cps == undefined) {
                    return;
                }
                var cpStr = '<option uid="" partnerId="" episodeType="' + VODNew.Config.PGC + '"></option>';
                //     var i = 0,
                var selected = '';

                $.each(cps, function (i, item) {
                    if (channel_name === item.channelalias) {
                        cpStr += '<option uid="' + item.ugcid + '"  selected  partnerId="' + item.qipuid + '" episodeType="' + VODNew.Config.UGC + '">' + item.ugcmsg + '</option>';
                        return false;
                    }
                })
                $('#cp').html(cpStr);
            });
        },


        compareTime: function (beginTime, endTime) {

            var beginTimes = beginTime.substring(0, 10).split('-');
            var endTimes = endTime.substring(0, 10).split('-');

            beginTime = beginTimes[1] + '-' + beginTimes[2] + '-' + beginTimes[0] + ' ' + beginTime.substring(10, 19);
            endTime = endTimes[1] + '-' + endTimes[2] + '-' + endTimes[0] + ' ' + endTime.substring(10, 19);

            var a = (Date.parse(endTime) - Date.parse(beginTime)) / 3600 / 1000;
            if (a < 0) {
                return -1;
            } else if (a > 0) {
                return 1;
            } else if (a == 0) {
                return 0;
            } else {
                return 'exception'
            }
        },
        detectZoom: function () {
            var ratio = 0,
                screen = window.screen,
                ua = navigator.userAgent.toLowerCase();

            if (window.devicePixelRatio !== undefined) {
                ratio = window.devicePixelRatio;
            } else if (~ua.indexOf('msie')) {
                if (screen.deviceXDPI && screen.logicalXDPI) {
                    ratio = screen.deviceXDPI / screen.logicalXDPI;
                }
            } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
                ratio = window.outerWidth / window.innerWidth;
            }

            if (ratio) {
                ratio = Math.round(ratio * 100);
            }

            return ratio;
        },
        browserZoomTips: function () {
            $('[role=alert1]').hide();
            if (VODNew.Util.detectZoom() > 100) {
                $('[role=alert]').html(VODNew.Config.ZOOM_HINT.BIG).show();
            } else if (VODNew.Util.detectZoom() < 100) {
                $('[role=alert]').html(VODNew.Config.ZOOM_HINT.SMALL).show();
            } else {
                $('[role=alert]').html("").hide();
            }
        },


        getPageRelativeMesurement: function () {
            return {
                width: $(window).width(),
                height: $(window).height()
            };
        },

        isJumpData: function (data, type) {
            if (type == 1) {
                var regJumpData = /^(\d{2}):(\d{2}):(\d{2})$/;
                if (!regJumpData.test(data)) {
                    return false;
                }
                return true;
            } else {
                if (isNaN(data)) {
                    return false;
                }
                return true;
            }
        },
        isVideoType1: function () {
            if ($('input[name=videotype]:checked').val() == -1)
                return 0;
            else
                return 1;
        },

        dealDirectionKey: function (arrow, settings) {
            if (!$(".red").is(":visible")) {
                return;
            }

            var currentTarget = parseInt($(".red").parent().find(".pid").text().replace(/\s+/g, ""));
            switch (arrow) {
                case  VODNew.Config.KEY_CODE.UP:
                    currentTarget = currentTarget - VODNew.Dao.settings.linePicNum;
                    break;
                case VODNew.Config.KEY_CODE.DOWN:
                    currentTarget = currentTarget + VODNew.Dao.settings.linePicNum;
                    break;
                case   VODNew.Config.KEY_CODE.LEFT:
                    currentTarget--;
                    break;
                case   VODNew.Config.KEY_CODE.RIGHT:
                    currentTarget++;
                    break;
            }
            if (currentTarget < 0) {
                currentTarget = 0;
            }
            $(".red").parent().find(".layout").removeClass("red").addClass("old");
            if (currentTarget >= parseInt($('#picNum').text())) {
                currentTarget = parseInt($('#picNum').text()) - 1;
            }
            settings.pic = settings.etime = settings.stime = currentTarget;
            var newTargetParent = $("#img-" + currentTarget).parent();
            if (newTargetParent.find(".layout").length > 0) {
                newTargetParent.find(".layout").addClass("red");
            } else {
                $(newTargetParent).append(VODNew.Config.RED_LAYOUT);
            }
            var offset = $(".red").offset();
            var heightLimit = $("#makedImg").height() - $(".red").height();
            if (offset.top < 22) {
                $("#makedImg").scrollTop(parseInt($("#makedImg").scrollTop() + offset.top - 22));
            }
            else if (offset.top > heightLimit) {
                $("#makedImg").scrollTop(parseInt($("#makedImg").scrollTop() + offset.top - heightLimit));
            }
        },
        setHighLight: function (rowData) {
            if (rowData != null) {
                var options = {};
                options.st = rowData.sTime
                options.et = rowData.eTime
                options.id = rowData.regId
                options.pic = rowData.pic
                VODCom.NewsHighlight.setHighLight(options);
            } else {
                VODCom.NewsHighlight.setHighLight(null);
            }
        },

        setMaskHighLight: function (rowData) {
            VODCom.NewsHighlight.clearMaskMark()
            if (rowData != null) {
                var options = {};
                if (rowData.sTime >= 0) {
                    options.maskST = rowData.sTime
                }
                if (rowData.eTime > 0) {
                    options.maskET = rowData.eTime
                }
                options.maskIndex = rowData.index
                VODCom.NewsHighlight.addInOutMaskMark(options)
            }
        },

        delFrame: function (rowId) {
            SystemDialog.queryConfirm("确认删除么?", function (flag) {
                if (flag === true) {
                    var findData = VODNew.Config.PageBeanFrame.findData("index", rowId);
                    if (findData != null) {
                        VODNew.Config.PageBeanFrame.delOne(findData)
                        VODNew.Util.updateGridFrame();
                    }
                }
            })
        },

        viewNews: function (rowId) {
            var findData = VODNew.Config.PageBeanNews.findData("regId", rowId);
            VODNew.Util.doReview(findData.sTime, findData.eTime, false)
        },

        viewNewsSubmit: function (rowId) {
            var findData = VODNew.Config.PageBeanNewsSubmit.findData("regId", rowId);
            if (findData == null) {
                console.log("no find data " + rowId);
                return;
            }
            VODNew.Util.doReview(findData.sTime, findData.eTime, false)
        },
        viewNewsDel: function (rowId) {
            var findData = VODNew.Config.PageBeanNewsDel.findData("regId", rowId);
            if (findData == null) {
                console.log("no find data " + rowId);
                return;
            }
            VODNew.Util.doReview(findData.sTime, findData.eTime, false)
        },


        delNews: function (rowId, skipQuery) {
            skipQuery = skipQuery === true ? true : false;
            var findData = VODNew.Config.PageBeanNews.findData("regId", rowId);
            var toRemoveArr = [];
            if (findData != null) {
                if (findData.isMergeMode) {
                    if (findData.toRemoveArr.length > 0) {
                        toRemoveArr = findData.toRemoveArr;
                    }
                } else if (findData.id > 0) {
                    toRemoveArr.push(findData.id);
                }
            }
            if (skipQuery) {
                VODNew.Util.delNewsMethod(toRemoveArr, findData);
            } else {
                SystemDialog.queryConfirm("确认删除该条新闻么?", function (flag) {
                    if (flag === true) {
                        VODNew.Util.delNewsMethod(toRemoveArr, findData);
                    }
                });
            }
        },
        delNewsMethod: function (toRemoveArr, findData) {
            VODNew.Dao.delNews({ key: VODNew.Dao.settings.taskid, id: toRemoveArr.join(","), status: 2, from_client: true }, function (data) {
                console.log(JSON.stringify(data));
                if (data.code == "A00000") {
                    VODNew.Plugin.tips("success", data.msg);
                    VODNew.Util.mockDelNews(findData.regId, true);
                } else {
                    VODNew.Plugin.tips("error", data.msg);
                }
            })
        },
        fillFormNews: function (rowId) {
            if (VODNew.Util.isAppendFragmentMode()) {
                return;
            }
            $(".ad-l").click();
            $(".ad-r").click();
            var findData = VODNew.Config.PageBeanNews.findData("regId", rowId);
            var panel = $("#cForm");
            panel.find("input[name=sTime]").val(findData.sTime);
            panel.find("input[name=eTime]").val(findData.eTime);
            panel.find("input[name=imageId]").val(findData.pic);
            panel.find("input[name=videoName]").val(findData.showTitle);
            panel.find("input[name=videoName]").change();
            this.recordImportData(rowId);
            //VODNew.Util.clearHighLight();
        },
        mockDelNews: function (rowId, skipAddToDelGrid) {
            var bdiv = $("#tab1").find(".ui-jqgrid-bdiv")
            var oldPosition = bdiv.scrollTop();
            var findData = VODNew.Config.PageBeanNews.findData("regId", rowId);
            VODNew.Config.PageBeanNews.delOne(findData);
            $("#news_list")[0].addJSONData(VODNew.Config.PageBeanNews.getCur());
            bdiv.scrollTop(oldPosition);
            if (skipAddToDelGrid == true) {
                return;
            }
            VODNew.Config.PageBeanNewsDel.addNewOne(findData);
            findData.index = VODNew.Dao.settings.newsDelIndex;
            VODNew.Dao.settings.newsDelIndex++;
            VODNew.Config.PageBeanNewsDel.sortData(VODNew.Config.SORT_RULE.desc_news_index)
            $("#auto_del_list")[0].addJSONData(VODNew.Config.PageBeanNewsDel.getCur());
            this.triggerNewsChange([rowId]);
        },
        cancelMergeDel: function (rowId) {
            var bdiv = $("#tab1").find(".ui-jqgrid-bdiv")
            var oldPosition = bdiv.scrollTop();
            var findData = VODNew.Config.PageBeanNewsDel.findData("regId", rowId);
            VODNew.Config.PageBeanNewsDel.delOne(findData);
            delete  findData.index;
            $("#auto_del_list")[0].addJSONData(VODNew.Config.PageBeanNewsDel.getCur());

            VODNew.Config.PageBeanNews.addNewOne(findData);
            VODNew.Config.PageBeanNews.sortData(VODNew.Config.SORT_RULE.asc_news_regId)
            $("#news_list")[0].addJSONData(VODNew.Config.PageBeanNews.getCur());
            bdiv.scrollTop(oldPosition);
        },
        delAdvert: function (rowId) {
            VODNew.Advert.delAdvert(rowId)
        },
        AlterTitle: function (rowId) {
            $("#alter_title-dlg").dialog("open");
            var rowData = VODNew.Config.PageBeanNews.findData("regId", rowId);
            var titleArr = JSON.parse(rowData.title);
            $("#alter_title-dlg").find("form").html("");
            var htmlArr = [];
            htmlArr.push('<input name="alter_title_id" type="hidden" value="' + rowId + '" />');
            $.each(titleArr, function (i, element) {
                htmlArr.push('<label><input type="radio" name="alter_title_radio" value="' + element + '" />' + element + '</label>')
            })
            $("#alter_title-dlg").find("form").html(htmlArr.join(""));
        },
        updateNewsGridRowData: function () {
            var selectedValue = $("input[name=alter_title_radio]:checked").val();
            if (selectedValue == null) {
                return;
            }
            var elementId = $("input[name=alter_title_id]").val();
            var rowData = VODNew.Config.PageBeanNews.findData("regId", elementId);
            if (rowData != null && rowData.showTitle != selectedValue) {
                rowData.showTitle = selectedValue;
                $("#news_list").setRowData(rowData.regId, { title: rowData.title, regId: rowData.regId });
            }
        },
        fromLIstJump: function (index) {
            if (!this.isJumpData(index, 0)) {
                //alert('跳转输入格式错误');
                VODNew.Plugin.tips("error", '跳转输入格式错误');
                return false;
            }
            var jumpContent = index + '-jump';
            if ($('.relative').hasClass(jumpContent)) {
                $('#makedImg').scrollTop(0)
                var sTop = $('.' + jumpContent).offset().top - 100;
                $('#makedImg').scrollTop(sTop);
            } else {
                //alert('没有这帧');
                VODNew.Plugin.tips("error", '没有这帧');
            }
        },
        initHelp: function () {
            var innerText = "";
            $.each(VODNew.Config.HELP_DATA, function (i, data) {
                innerText += '<tr><td>' + data[0] + '</td><td>' + data[1] + '</td></tr>'
            })
            $("#help-dlg").find("tbody").html(innerText);
            if ($("#help2-dlg").length > 0) {
                innerText = "";
                $.each(VODNew.Config.HELP2_DATA, function (i, data) {
                    innerText += '<tr><td>' + data[0] + '</td><td>' + data[1] + '</td></tr>'
                })
                $("#help2-dlg").find("tbody").html(innerText);
            }
        },
        validStart: function () {
            var self = this;
            var settings = VODNew.Dao.settings;
            if (VODNew.Config.EDIT_MODE_TYPE == 1) {
                var s_time = $('#inputStartTime').val();
                var e_time = $('#inputEndTime').val();
                var checkArr = [];
                checkArr.push({value: s_time.length, error: "请先输入起始时间", type: "gt", other: 0 })
                checkArr.push({value: e_time.length, error: "请先输入结束时间", type: "gt", other: 0 })
                checkArr.push({value: s_time, error: "起始时间格式不正确", type: "date"})
                checkArr.push({value: e_time, error: "结束时间格式不正确", type: "date"})
                checkArr.push({value: s_time, error: "开始时间必须小于结束时间", type: "lt", other: e_time })
                checkArr.push({value: s_time, error: "开始时间不能大于当前时间", type: "lt", other: this.formatDateTimeFormat(new Date()) });
                if (!VODNew.Plugin.Validate.batchCheck(checkArr)) {
                    console.log("interrupt checkLiveType checkRepeat")
                    return false;
                }
                settings.period = parseInt((self.dateToNumber(e_time) - self.dateToNumber(s_time)) / 1000);
                settings.today = s_time.replace(/-/g, '').substring(0, 8);
                settings.startQuery = parseInt(this.dateToNumber(s_time) / 1000);
                return   settings.startQuery;
            } else if (VODNew.Config.EDIT_MODE_TYPE == 2) {
                return true;
            }
            return false;

        },
        dateToNumber: function (dString) {
            var toDate = new Date(dString.replace(/-/g, "/"));
            return toDate.getTime();
        },
        getLineWidth: function () {
            var settings = VODNew.Dao.settings;
            var lineWidth = $('.img-content').width();
            var picWidth = $('.relative').width();
            settings.linePicNum = parseInt(lineWidth / picWidth);
        },
        dl_click: function (clt) {
            try {
                if (clt == '') {
                    return;
                }
                var Then = new Date();
                var continued_time = Math.round((Then.getTime()) / 1000);
                $.get(clt + "&ct=" + continued_time);
            }
            catch (e) {
                console.log("error", e);
            }
        },
        dl_img_click: function (event, viewTime) {
            var element = $(event.currentTarget);
            var options ={
                url:  element.attr("src").replace(/jpg/g, "flv"),
                name:    $(event.currentTarget).attr("id").replace("img-",""),
                duration :   element.attr("duration")
            }
            VODCom.Player.view(viewTime,options)
        },

        validAddInfo: function (data) {
            var v = true;
            $.each(data, function (message, type) {
                if (type == null || type.length == 0) {
                    VODNew.Plugin.tips("error", message + '不存在，请重新输入');
                    v = false;
                    return false;
                }
            });
            return v;
        },
        addInfo: function (data, type) {
            data.sTime = parseInt(data.sTime);
            data.eTime = parseInt(data.eTime);
            if (type == 'add') {
                $('#addInfo').html('成功');

                VODNew.Config.PageBeanFrame.addNewOne(data);
                VODNew.Util.updateGridFrame();
                this.notifyAddNewsSubmit(data);
            }
        },


        getDataByNum: function (period) {
            var second = period % 60;
            var minute = ( period % 3600 - period % 60) / 60;
            var hour = (period - period % 3600) / 3600;
            return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + ":" + (second < 10 ? "0" + second : second);
        },

        //提交删除
        checkStAndEt: function (stime, etime, plusMsg) {
            plusMsg = plusMsg || "";
            var checkArr = [];
            checkArr.push({value: stime, error: plusMsg + "起始帧有误,必须为数字类型", type: "number"})
            checkArr.push({value: etime, error: plusMsg + "结束帧有误,必须为数字类型", type: "number"})
            checkArr.push({value: parseInt(stime), error: plusMsg + "起始帧需要小于结束帧", type: "lt", other: parseInt(etime)  })
            return VODNew.Plugin.Validate.batchCheck(checkArr)
        },


        //提交拆条
        dot_submit: function () {
            var settings = VODNew.Dao.settings;
            VODNew.Config.LAST_SUBMIT_TIME = VODNew.Config.DOT_SUBMIT_TIME;
            VODNew.Config.DOT_SUBMIT_TIME = this.formatDateTimeFormat(new Date());
            var paramsData = VODNew.Dao.getParamsData();
            var global = VODNew.Config.Global;
            if (settings.taskid < 1.) {
                VODNew.Plugin.tips("error", '任务ID为空,不能提交!');
                return false;
            }
            if ($("span[span-mode=warn]").is(":visible")) {
                VODNew.Plugin.tips("error", '标题过长,不能提交!');
                return false;
            }
            var source = VODNew.Config.PageBeanMaskEntity.getSource();
            if (!VODNew.MaskManager.isValidDelogo(source)) {
                VODNew.Plugin.tips("error", '遮标数据出点入点都必须大于零，且入点不大于出点');
                return  false;
            }


            $('input[name=imageId]').val($('input[name=imageId]').val().trim());
            var sTime = $('input[name=sTime]').val(),
                eTime = $('input[name=eTime]').val(),
                title = $('input[name=videoName]').val(),
                channel = $('input[name=categoryName]').suggest("getValue");
            var cname = $('input[name=categoryName]').val();
            var cpOption = $('#cp').children('option:selected');
            var album = $('input[name=albumName]').val(),
                pic = $('input[name=imageId]').val() ? $('input[name=imageId]').val() : sTime,
                fantasyTitle = $('input[name=fantasyTitle]').val() ? $('input[name=fantasyTitle]').val() : "",
                data = {
                    '起始帧': sTime,
                    '结束帧': eTime,
                    '标题': title,
                    '频道': channel
                },
                dataSubmit = {
                    'index': settings.index,
                    'sTime': sTime,
                    'eTime': eTime,
                    'title': title,
                    'channel': channel,
                    'album': album,
                    'pic': pic
                }

            if (VODNew.Config.FORCE_CHECK_IMAGE.hasOwnProperty("tag" + channel)) {
                if ($('input[name=imageId]').val().length == 0) {
                    VODNew.Plugin.tips("error", "请人工选择封面图！");
                    return false;
                }
            }
            if (this.hasImportData()) {
                dataSubmit.importRegId = parseInt($("span[name=import-id-span]").attr("import-data-id"));
            }
            var toLego = true,
                priority = $('input[name=priority]:checked').val(), //优先级
                video_dpi = $('input[name=video_dpi]:checked').val(), //分辨率
                isVolumeStandard = $('input[name=isVolumeStandard]:checked').val(), //音量标准化参数
                isVolumeStandardForMaterial = $('input[name=isVolumeStandardForMaterial]:checked').val(),
                uid = cpOption.attr("uid"), //表示ugc用户id
                partnerId = cpOption.attr("partnerId"), //表示合作方id
                episodeType = cpOption.attr("episodeType"); //取值为0或1,1表示为ugc视频，0为普通ppc视频


            uid = !uid ? "" : uid;
            partnerId = !partnerId ? "" : partnerId;
            episodeType = !episodeType ? "" : episodeType;
            var albumId = '';
            if (album) {
                albumId = $('input[name=albumName]').suggest("getValue") || "";
                //  $('input[name=albumId]').val();
            }


            if (!this.checkStAndEt(sTime, eTime)) {
                return false;
            }
            if (VODNew.Util.isAppendFragmentMode()) {
                if (!VODNew.Util.checkFragmentEnd(eTime)) {
                    return false;
                }
            }
            var checkArr = [];
            checkArr.push({value: pic, error: "封面格式有误,必须为数字类型", type: "number"})
            checkArr.push({value: parseInt(pic), error: "封面不能小于起始帧", type: "ge", other: parseInt(sTime)});
            checkArr.push({value: parseInt(pic), error: "封面不能大于结束帧", type: "le", other: parseInt(eTime)})
            var numTime = $('#picNum').text();
            checkArr.push({value: parseInt(eTime), error: "结束帧不存在,不能提交", type: "lt", other: parseInt(numTime)  })
            if (!VODNew.Plugin.Validate.batchCheck(checkArr)) {
                console.log("interrupt checkLiveType checkRepeat")
                return false;
            }
            $('#addInfo').attr('disabled', 'disabled');
            if (!toLego) {
                return;
            }
            if (!this.validAddInfo(data)) {
                return false;
            }
            var needMark = true;
            if (this.hasImportData()) {
                var importData = VODNew.Config.PageBeanNews.findData("regId", parseInt($("span[name=import-id-span]").attr("import-data-id")))
                if (parseInt(dataSubmit.eTime) == importData.eTime) {
                    needMark = false;
                }
            }
            if (needMark) {
                var aframeData = VODNew.AccurateFrame.getAccurateFrame();
                if (aframeData.endSetted && aframeData.endPic == parseInt(dataSubmit.eTime)) {
                    needMark = false;
                }
            }
            if (needMark) {
                //alert("请在片尾使用精确化裁剪工具，快捷键Q");
                VODNew.Plugin.tips("error", "请在出点使用精确化裁剪工具，快捷键Q");
                return false;
            }

            //去除删除部分
            VODCom.Player.splitData(sTime, eTime, true);
            console.log(settings.subData);
            if (!settings.subData.length) {
                //alert('该条打了删除，不能再打拆条!');
                VODNew.Plugin.tips("error", '该条打了删除，不能再打拆条!');
                return false;
            }
            //未制作成片节目
            //提交数据到乐高
            // var p_vid = $('input[name=videoId]').val() ? $('input[name=videoId]').val() : 0;
            var p_vid = $('input[name=videoName]').suggest("getValue") || 0;
            var p_albumId = $('input[name=albumName]').suggest("getValue") || "";
            var videotype = $('input[name=videotype]:checked').val();
            if (videotype == -1) {
                p_vid = 0;
                var bind_sel_name = $('input[name=categoryName]').attr("bind-sel-name");
                var bind_sel_id = $('input[name=categoryName]').attr("bind-sel-id");
                if (bind_sel_name == null || bind_sel_name == "" || cname != bind_sel_name) {
                    VODNew.Plugin.tips("error", '提交失败，频道不存在!');
                    return false;
                }
            } else if (videotype == 0 || videotype == 1) {
                var bind_sel_name = $('input[name=videoName]').attr("bind-sel-name");
                var bind_sel_id = $('input[name=videoName]').attr("bind-sel-id");
                if (bind_sel_name == null || bind_sel_name == "" || title != bind_sel_name) {
                    VODNew.Plugin.tips("error", '提交失败，标题不存在!');
                    return false;
                }
            }

            var dadianmerge = {ocr_flag: 0, intelligent_insert_time: ""};
            if (this.hasImportData()) {
                dadianmerge.ocr_flag = 1;
                dadianmerge.intelligent_insert_time = $("span[name=import-id-span]").attr("import-data-time");
            } else {
                dadianmerge.intelligent_insert_time = VODNew.Config.LAST_SUBMIT_TIME;
            }

            if (VODNew.Config.fragmentPid > 0) {
                p_vid = VODNew.Config.fragmentPid;
                if (!this.hasImportData()) {
                    dadianmerge.intelligent_insert_time = VODNew.Config.FIRST_FRAGMENT_START;
                }
            }

            var handlerPostData = function (programId) {
                var newPA = {
                    title: title,
                    cat: channel,
                    alb: albumId,
                    enableClound: VODNew.Util.getEnableCloundVal(),
                    priority: priority,
                    video_dpi: video_dpi,
                    uid: uid,
                    partnerId: partnerId,
                    episodeType: episodeType
                }
                if (videotype == -1) {
                    newPA.fantasyTitle = fantasyTitle;
                } else if (videotype == 1) {
                    newPA.reTranscodeConfirm = VODNew.Util.getReTranscodeConfirmVal();
                }

                VODNew.Util.postData(settings.subData, newPA, pic, programId, dataSubmit, function (flag) {
                    //提交数据给刘之红
                    if (flag) {
                        var stData = $.extend(true, {}, dataSubmit, { programId: programId, cname: cname })
                        //     VODNew.Util.doSt1Data(advertParams.delAdStr, stData, dadianmerge);
                        VODNew.Util.doSt1Data(0, stData, dadianmerge);// 不使用 advertParams.delAdStr
                        VODNew.Config.OCR_TITLE_FLAG = 0;
                        VODCom.AutoTitle.clearData();
                        VODNew.Util.doSt2Data(stData);
                        //alert('打点成功');
                        VODNew.Plugin.tips("success", '打点成功');
                        VODNew.AccurateFrame.fgTipRemove();
                        VODNew.MaskManager.clearMaskEntity();
                        VODNew.AccurateFrame.adTipRemove();
                        console.log("[handlerPostData] handler suc")
                    } else {
                        console.log("[handlerPostData] handler fail")
                    }
                });
            }

            // dealroute 针对是否需要申请 programId
            var dealRoute = -1; //分片未提交
            if (VODNew.Config.lastLegoSubmitObj.programId != VODNew.Config.fragmentPid) {
                VODNew.Config.lastLegoSubmitObj.programId = VODNew.Config.fragmentPid;
                VODNew.Config.lastLegoSubmitObj.hasSubmit = false;
                dealRoute = 1;
            } else if (VODNew.Config.lastLegoSubmitObj.hasSubmit == false) {
                dealRoute = 2; // 如果 尚未提交过
            } else {
                dealRoute = 3; //  分片提交过
            }

            if (dealRoute == 1 || dealRoute == 2) {
                var dataJson = {
                    'videoId': p_vid,
                    'priority': priority,
                    'albumName': album,
                    'videoName': title,
                    'categoryId': channel,
                    'albumId': p_albumId,
                    'reTranscodeConfirm': VODNew.Util.getReTranscodeConfirmVal(),
                    'freeType': paramsData.freeType,
                    'isVolumeStandard': isVolumeStandard,
                    isVolumeStandardForMaterial: isVolumeStandardForMaterial,
                    userArea: VODNew.Util.getUserRegion()
                };
                if ($("#locationDiv").is(":visible")) {
                    dataJson.locationCategory = $("input[name=location]").suggest("getValue");
                }
                if (videotype == -1) {
                    dataJson.fantasyTitle = fantasyTitle;
                }
                // settings.videonameArr = [];

                var sendData = {"request": JSON.stringify({url: VODNew.Constant.thirdUrl_peditor_submit, type: "post", params: {
                    data: JSON.stringify(dataJson)
                }, needCookie: true}), timeSign: new Date().getTime()}
                VODNew.Dao.dopeditorSubmit(sendData, {
                    doSuc: function (res) {
                        if (res == null || res.code != 'A00000') {
                            VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.sendProgramDataToLego, sendData, res, "fromUrl:" + VODNew.Constant.thirdUrl_peditor_submit);
                            VODNew.Plugin.tips("error", res == null ? "lego接口无效返回值" : "lego错误：" + res.msg);
                            if (VODNew.Util.isAppendFragmentMode()) {
                                $('input[name=isAppendFragment]').removeAttr("disabled");
                                $('input[name=isAppendFragment][value="0"]').click();
                                //     VODNew.Util.transToNormalMode();
                            }
                        } else {

                            var programId = res.data.programId;
                            if (!programId) {
                                VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.sendProgramDataToLego, sendData, {error: '乐高返回的programId为空!'}, "fromUrl:" + VODNew.Constant.thirdUrl_peditor_submit);
                                //alert('乐高返回的programId为空!');
                                VODNew.Plugin.tips("error", '乐高返回的programId为空!');
                                return false;
                            }
                            VODNew.Util.episodeLogSubmit(programId, VODNew.Config.VOD_LOG_TYPE.sendProgramDataToLego, sendData, res, "fromUrl:" + VODNew.Constant.thirdUrl_peditor_submit);
                            VODNew.Config.fragmentPid = programId;
                            VODNew.Config.lastLegoSubmitObj.programId = VODNew.Config.fragmentPid;
                            VODNew.Config.lastLegoSubmitObj.hasSubmit = true;
                            handlerPostData(programId)
                        }
                    },
                    doError: function (XMLHttpRequest, status) {
                        VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.sendProgramDataToLego, dataJson, { type: "error reqeust", status: status }, "fromUrl:" + VODNew.Constant.thirdUrl_peditor_submit);
                        VODNew.Plugin.tips("error", '网络错误,请稍后再提交！');
                        //              VODNew.Plugin.tips("error", '接口/peditor/submit调用超时10秒未响应！请联系乐高相关负责人员！');
                    }
                })
            } else if (dealRoute == 3) {
                handlerPostData(p_vid)
            }
        },

        // 获取字符串长度
        subCharacterLength: function (str, charLength) {
            var titleReg = new RegExp("[\\u4E00-\\u9FFF]");
            var countLength = 0;
            var indexCount = 0;
            var tmpLength = 0;
            for (var i = 0, l = str.length; i < l; i++) {
                // 0-127 ASCII char
                // 128-255 ASCII expand char
                if (str.charCodeAt(i) > 255) {
                    tmpLength = 2;
                } else {
                    tmpLength = 1;
                }
                if (countLength + tmpLength > charLength) {
                    break;
                }
                indexCount++;
                countLength += tmpLength;
            }
            return str.substr(0, indexCount);
        },

        // 填加背景色
        addBackgroundColor: function (options) {
            var defaults = {
                st: 0,
                et: 0,
                color: '',
                removeColor: ''
            };
            options = $.extend({}, defaults, options);

            for (var i = options.st; i <= options.et; i++) {
                if (!options.removeColor) {
                    $('#img-' + i).addClass(options.color);
                } else {
                    $('#img-' + i).removeClass(options.color);
                }
            }
        },

        fetchDelogoArr: function (list) {
            //   return VODNew.MaskManager.getPicDropList(list[0], list[list.length -1]);
            var source = VODNew.MaskManager.makeUpSubDelogoArr();
            var subList = list;
            var retArr = [];
            var ableElement = null;
            $.each(source, function (i, element) {
                ableElement = VODNew.Util.filterEnableDelogo(element, subList);
                if (ableElement != null) {
                    retArr.push(ableElement);
                }
            })
            return retArr;
        },
        filterEnableDelogo: function (element, subList) {
            var min = subList[0];
            var max = subList[subList.length - 1];
            var finalObj = {st: element.st, et: element.et, coverArr: element.coverArr };
            while (subList.indexOf(finalObj.st) == -1) {
                finalObj.st++;
                if (finalObj.et != -1 && finalObj.st > finalObj.et) {
                    return null;
                }
                if (finalObj.st > max) {
                    return null;
                }
            }
            if(finalObj.et != -1){
                while (subList.indexOf(finalObj.et) == -1) {
                    finalObj.et--;
                    if (finalObj.et < finalObj.st) {
                        return null;
                    }
                    if (finalObj.et < min) {
                        return null;
                    }
                }
            }
            console.log("finalObj st:" + finalObj.st, ",et:" + finalObj.et + "|| element st:" + element.st + ",et" + element.et);
            return finalObj;
        },

        postData: function (list, newPA, imageId, programId, addData, handler) {
            var sList = '[' + list.join(",") + "]";
            var paramsData = VODNew.Dao.getParamsData();
            var settings = VODNew.Dao.settings;
            var accurateFrame = VODNew.AccurateFrame.getAccurateFrame();
            var dotData = VODNew.Dao.getDotData();
            var pData = {
                'title': newPA.title,
                'categoryId': newPA.cat,
                'albumId': newPA.alb,
                'code': paramsData.channel_name,
                'programId': programId,
                'userId': VODNew.Util.getUserId() + "",
                'from_client': true,
                'key': settings.taskid,
                'list': sList,
                'imageId': imageId,
                'head': accurateFrame.head,
                'end': accurateFrame.end,
                'priority': newPA.priority,
                'video_dpi': newPA.video_dpi,
                'uid': newPA.uid,
                'partnerId': newPA.partnerId,
                'episodeType': newPA.episodeType,
                'enableClound': newPA.enableClound,
                'needRemakeVideo': VODNew.Util.getNeedRemakeVideo(),
                'delogoArr': JSON.stringify(VODNew.Util.fetchDelogoArr(list))
            };

            if ("fantasyTitle" in newPA) {
                pData.fantasyTitle = newPA.fantasyTitle;
            }
            if ("reTranscodeConfirm" in newPA) {
                if (VODNew.Config.lastSubmitObj.programId != programId || VODNew.Config.lastSubmitObj.hasSubmit == false) {
                    VODNew.Config.lastSubmitObj.programId = programId;
                    VODNew.Config.lastSubmitObj.hasSubmit = true;
                    pData.reTranscodeConfirm = newPA.reTranscodeConfirm;
                }
            }

            var appendMode = VODNew.Util.isAppendFragmentMode();
            if (appendMode) {
                pData.tag = 1;
            }

            VODNew.AccurateFrame.doReset();
            var sendUrl = !appendMode ? dotData.dotUrl : dotData.appendUrl;
//            var hackData = $.extend(true,{},pData);
//            hackData.list = [-1].concat(     hackData.list );
            VODNew.Dao.postSync(sendUrl, pData, {
                doSuc: function (data) {
                    VODNew.Util.episodeLogSubmit(programId, VODNew.Config.VOD_LOG_TYPE.submitDotData, pData, data, "url:" + sendUrl);
                    if (data == null || data.error != 0) {
                        VODNew.Plugin.tips("error", data == null ? "提交打点无效返回值" : "提交打点错误:" + data.error);
                        handler(true);
                    } else {
                        VODNew.Config.lastSubmitObj = { programId: -1, hasSubmit: false}
                        VODNew.Config.lastLegoSubmitObj = { programId: -1, hasSubmit: false}
                        VODNew.Config.fragmentPid = 0;
                        VODNew.Util.doResetCForm("saveCategoryName");
                        VODNew.Util.setHighLight(null);
                        $('#addInfo').html('成功');
                        VODNew.Util.addInfo(addData, 'add');
                        settings.index++;
                        handler(true);
                    }
                },
                doError: function () {
                    VODNew.Util.episodeLogSubmit(programId, VODNew.Config.VOD_LOG_TYPE.submitDotData, pData, {type: "request error"}, "url:" + sendUrl);
                    VODNew.Plugin.tips("error", '编码服务器网络错误,请稍后再提交！');
                    $('#addInfo').removeAttr('disabled').html('提交');
                    handler(false);
                }
            }, false)
//                    VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.submitDotData, pData, {type: "request error"}, "url:" + sendUrl);
//                    VODNew.Plugin.tips("error", '编码服务器网络错误,请稍后再提交！');
//                    $('#addInfo').removeAttr('disabled').html('提交');
//                    handler(true);
        },


        doReview: function (sTime, eTime, deleteFlag) {
            var data = {
                '起始帧': sTime,
                '结束帧': eTime
            };
            if (!VODNew.Util.validAddInfo(data)) {
                return false;
            }
            if (parseInt(sTime) > parseInt(eTime)) {
                VODNew.Plugin.tips("error", '起始帧不能大于结束帧');
                return false;
            }
            var numTime = $('#picNum').text();
            if (parseInt(eTime) >= parseInt(numTime)) {
                VODNew.Plugin.tips("error", '结束帧不存在,不能预览');
                return false;
            }
            VODCom.Player.splitData(sTime, eTime, deleteFlag); //去除删除部分
            VODCom.Player.review();
        },

        getReTranscodeConfirmVal: function () {
            return  $('input[name=reTranscodeConfirm]').is(":checked") ? 1 : 0
        },
        getEnableCloundVal: function () {
            return  $('input[name=enableClound]').is(":checked") ? 0 : 1
        },
        getUserId: function () {
            return auth.baseInfo.authInfo.uid;
        },
        getUserName: function () {
            return auth.baseInfo.authInfo.userName;
        },

        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多字字符数（一个汉字等于两个字符）
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        limitWordCount: function ($des, charCount, isFilterChars, filterChars, bindHandler) {
            var self = this;
            charCount = charCount || 450;
            var t = function (textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > charCount) {
                    $textarea.val(self.subCharacterLength(text, charCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                if (bindHandler == null) {
                    $textarea.parent().find('span.leftWordsCount').text(charCount - length);
                } else {
                    bindHandler(charCount - length);
                }
            };
            $des.bind({
                input: function () {
                    //   console.log("input handler ")
                    t(this);
                },
                propertychange: function () {
                    t(this);
                },
                change: function () {
                    t(this);
                },
                focusout: function () {
                    setTimeout(function () {
                        t($des)
                    }, 100);
                },
                keyup: function () {
                    t(this);
                }
            });
            $des.keyup();
        },


        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多字字符数（一个汉字等于两个字符）
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        canOverWordCount: function ($des, charCount, isFilterChars, filterChars, bindHandler) {
            var self = this;
            charCount = charCount || 450;
            var t = function (textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (bindHandler != null) {
                    bindHandler(charCount - length);
                }
            };
            $des.bind({
                input: function () {
                    t(this);
                },
                propertychange: function () {
                    t(this);
                },
                change: function () {
                    t(this);
                },
                focusout: function () {
                    setTimeout(function () {
                        t($des)
                    }, 100);
                },
                keyup: function () {
                    t(this);
                }
            });
            $des.keyup();
        },

        binSearchOcrTitle: function (start, end) {
            return this.binSearchTitle(VODNew.Dao.settings.g_ocrList, start, end)
        },
        binSearchAcrTitle: function (start, end) {
            return this.binSearchTitle(VODNew.Dao.settings.g_acrList, start, end)
        },
        binSearchTitle: function (arr, start, end) {
            var titleList = [];
            var tmp = [];
            var len = arr.length;
            if (len) {
                for (var i in arr) {
                    if (start >= arr[i]['first'] && start <= arr[i]['last'] || arr[i]['first'] >= start && arr[i]['last'] <= end || end >= arr[i]['first'] && end <= arr[i]['last']) {
                        tmp[arr[i]['title']] = i; // 去重复
                    }
                }
                for (var j in tmp) {
                    titleList.push(j);
                }
            }
            return titleList;
        },
        updateGridAdvert: function () {
            $('#advert_list').clearGridData();
            $('#advert_list')[0].addJSONData(VODNew.Config.PageBeanAdvert.getCur())
        },
        updateGridFrame: function () {
            $('#frame_list').clearGridData();
            $('#frame_list')[0].addJSONData(VODNew.Config.PageBeanFrame.getCur())
        },
        updateGridNewsSubmit: function () {
            $('#auto_submit_list').clearGridData();
            $('#auto_submit_list')[0].addJSONData(VODNew.Config.PageBeanNewsSubmit.getCur())
        },

        updateGridNewsDel: function () {
            $('#auto_del_list').clearGridData();
            $('#auto_del_list')[0].addJSONData(VODNew.Config.PageBeanNewsDel.getCur())
        },
        updateGridMaskEntity: function () {
            $('#mask_list').clearGridData();
            $('#mask_list')[0].addJSONData(VODNew.Config.PageBeanMaskEntity.getCur())
        },
        updateCForm: function (updateObj) {
            if (updateObj.hasOwnProperty("eTime")) {
                $("#cForm").find("input[name=eTime]").val(updateObj.eTime)
            }
            if (updateObj.hasOwnProperty("sTime")) {
                $("#cForm").find("input[name=sTime]").val(updateObj.sTime)
            }
            if (updateObj.hasOwnProperty("pic")) {
                $("#cForm").find("input[name=imageId]").val(updateObj.pic)
            }
        },
        updateObjectData: function (newData, oldData) {
            for (var key in newData) {
                if (oldData.hasOwnProperty(key)) {
                    oldData[key] = newData[key];
                }
            }
        },


        doRowSelected: function (element) {
            var tempChild = VODNew.Config.PageBeanNews.findData("regId", parseInt(element.value));
            tempChild.checked = $(element).is(":checked");
        },
        doSelectedAll: function (flag) {
            var elementArr = $("#news_list").find("input[type=checkbox]");
            $.each(elementArr, function (i, element) {
                if ($(element).is(":checked") == !flag) {
                    $(element).click();
                }
            })
        },

        doQuickMerge: function () {
            var selElementArr = $("#news_list").find("input[type=checkbox]:checked");
            var childArr = [];
            var tempChild = null;
            $.each(selElementArr, function (i, elem) {
                tempChild = VODNew.Config.PageBeanNews.findData("regId", parseInt(elem.value));
                childArr.push(tempChild);
            })
            childArr.sort(VODNew.Config.SORT_RULE.asc_news_sTime);
            if (childArr.length == 1) {
                return;
            }
            var checkContinue = -1;
            var toRemoveArr = [];
            var newTitleArr = [];
            var childTitleArr = null;
            var endFrameData = null;
            $.each(childArr, function (i, tempChild) {
                if (checkContinue == -1) {
                    checkContinue = tempChild.eTime;
                    endFrameData = tempChild.frameData;
                } else if (checkContinue + 1 >= tempChild.sTime) {
                    if (checkContinue < tempChild.eTime) {
                        checkContinue = tempChild.eTime;
                        endFrameData = tempChild.frameData;
                    } else if (endFrameData == null) {
                        endFrameData = tempChild.frameData;
                    } else {
                        if (tempChild.frameData != null && tempChild.frameData.end != endFrameData.end) {
                            console.log("结尾关键帧不同，清空")
                            endFrameData = null;
                        }
                    }
                } else {
                    VODNew.Plugin.tips("error", "条目不连续，不能合并");
                    checkContinue = -2;
                    return false
                }
                if (tempChild.id > 0) {
                    toRemoveArr.push(tempChild.id);
                } else if (tempChild.isMergeMode) {
                    toRemoveArr = toRemoveArr.concat(tempChild.toRemoveArr);
                }
                childTitleArr = JSON.parse(tempChild.title);

                if (childTitleArr.length > 0) {
                    if (tempChild.showTitle != "") {
                        if (childTitleArr.indexOf(tempChild.showTitle) == -1) {
                            childTitleArr = [ tempChild.showTitle ].concat(childTitleArr);
                        }
                    }
                    newTitleArr = newTitleArr.concat(childTitleArr);
                } else {
                    if (tempChild.showTitle != "") {
                        newTitleArr.push(tempChild.showTitle);
                    }
                }
            });
            if (checkContinue > 0) {
                var firstData = childArr[0];
                var newObj = {title: JSON.stringify(newTitleArr), sTime: firstData.sTime, eTime: checkContinue,
                    pic: firstData.pic, regId: firstData.regId, id: 0,
                    isMergeMode: true, children: childArr, toRemoveArr: toRemoveArr,
                    frameData: endFrameData
                };
                $("#news_list").clearGridData();
                VODNew.Util.mergeNewsGridData([newObj], childArr)
                VODNew.Util.setHighLight(newObj);
                VODNew.Util.fromLIstJump(newObj.sTime);
                VODNew.Util.doNewsGridScroll(newObj.regId);
                $("#news_list").jqGrid('setSelection', newObj.regId);
            }
        },
        doChangeTitle: function (element) {
            var $target = $(element);
            var targetId = null;
            targetId = parseInt($target.attr("data-id"))
            var rowData = VODNew.Config.PageBeanNews.findData("regId", targetId);
            rowData.showTitle = $target.val();
            $("#news_list").setRowData(rowData.regId, { title: rowData.title, regId: rowData.regId });
        },
        undoMerge: function (mergeId) {
            var rowData = VODNew.Config.PageBeanNews.findData("regId", parseInt(mergeId));
            $.each(rowData.children, function (i, element) {
                element.checked = false;
            })
            VODNew.Util.mergeNewsGridData(rowData.children, [rowData])
            VODNew.Util.clearHighLight();
            VODNew.Util.doNewsGridScroll(mergeId);

        },
        mergeNewsGridData: function (addArr, delArr) {
            var notifyArr = [];
            $.each(delArr, function (i, element) {
                VODNew.Config.PageBeanNews.delOne(element);
                notifyArr.push(element.regId);
            })
            $.each(addArr, function (i, element) {
                VODNew.Config.PageBeanNews.addNewOne(element);
            })
            VODNew.Config.PageBeanNews.sortData(VODNew.Config.SORT_RULE.asc_news_regId);
            $("#news_list")[0].addJSONData(VODNew.Config.PageBeanNews.getCur());
            VODNew.Util.triggerNewsChange(notifyArr);
        },
        clearHighLight: function () {
            VODCom.NewsHighlight.setHighLight(null);
        },
        doNewsGridScroll: function (rowid) {
            var bdiv = $("#tab1").find(".ui-jqgrid-bdiv");
            if (bdiv[0].scrollHeight <= bdiv[0].clientHeight) {
                return;
            }
            rowid = rowid + ""
            var allData = $("#news_list").jqGrid("getRowData");
            var interrupt = 0;
            for (var i = 0; i < allData.length; i++) {
                if (allData[i].hidden_news_id == rowid) {
                    interrupt = i;
                    break;
                }
            }
            bdiv.scrollTop(interrupt / allData.length * bdiv[0].scrollHeight);
        },
        hasIntelligentData: function () {
            $("#contains_news_list").show();
            $("hr:eq(0)").show();
        },
        nonIntelligentData: function () {
            $("#contains_news_list").hide();
            $("hr:eq(0)").hide()
        },
        doResetCForm: function (mode) {

            var saveData = null;
            if (mode == "saveCategoryName") {
                saveData = {};
                saveData.id = parseInt($('input[name=categoryName]').suggest("getValue"));
                saveData.label = $('input[name=categoryName]').val();
            }
            var locationVal = $("input[name=location]").val();
            $("#cForm")[0].reset();
            if (saveData != null) {
                $('input[name=categoryName]').suggest("setValue", saveData);
            }
            $('input[name=videoName]').suggest("setValue", "");
            $("input[name=albumName]").suggest("setValue", "");
            $("input[name=location]").val(locationVal);
            this.doClearImportData();
            $("input[name=videoName]").change();
            $("input[name=fantasyTitle]").change();
            $("#locationDiv").hide();
            $("input[name=videotype][value='-1']").click();
            $("input[name=isAppendFragment][value='0']").click()
        },

        doClearImportData: function (clearMode) {
            if (clearMode != null && clearMode == "all") {
                this.doResetCForm();
            } else {
                $("div[import-id-div=true]").hide();
                $("span[name=import-id-span]").html("");
                $("span[name=import-id-span]").removeAttr("import-data-id");
                $("span[name=import-id-span]").removeAttr("import-data-time");
            }
        },
        doResetDForm: function () {
            $("#dForm")[0].reset();
        },
        clearOldTaskData: function () {
            VODNew.Util.nonIntelligentData();
            VODNew.Config.PageBeanNews.setNewData([], 100);
            VODNew.Util.doResetCForm();
            VODCom.AutoTitle.clearData()
        },
        recordImportData: function (rowId) {
            $("div[import-id-div=true]").show();
            $("span[name=import-id-span]").html(rowId);
            $("span[name=import-id-span]").attr("import-data-id", rowId);
            $("span[name=import-id-span]").attr("import-data-time", this.formatDateTimeFormat(new Date()));
        },
        triggerNewsChange: function (targetArr) {
            if (targetArr.length > 0 && this.hasImportData()) {
                var elementId = $("span[name=import-id-span]").attr("import-data-id");
                if (targetArr.indexOf(parseInt(elementId)) != -1) {
                    console.log(" triggerNewsChange " + elementId)
                    this.doResetCForm();
                }
            }
        },
        notifyAddNewsSubmit: function (data) {
            if (data.importRegId && data.importRegId > 0) {
                var ocrFlagData = $.extend(true, {}, data);
                ocrFlagData.index = VODNew.Dao.settings.newsSubmitIndex;
                VODNew.Dao.settings.newsSubmitIndex++;
                VODNew.Config.PageBeanNewsSubmit.addNewOne(ocrFlagData);
                VODNew.Config.PageBeanNewsSubmit.sortData(VODNew.Config.SORT_RULE.desc_news_index);
                VODNew.Util.updateGridNewsSubmit();
                VODNew.Util.delNews(data.importRegId, true)
            }
        },
        hasImportData: function () {
            return $("span[name=import-id-span]").is(":visible")
        },
        doSourceRemove: function (removeArr, newSource) {
            var pageBean = VODNew.Util.createPageBean();
            pageBean.setNewData(newSource);
            var removeArrIdArr = [];
            $.each(removeArr, function (i, element) {
                if (element.isMergeMode) {
                    removeArrIdArr = removeArrIdArr.concat(element.toRemoveArr);
                } else {
                    removeArrIdArr.push(element.id);
                }
            })
            $.each(removeArrIdArr, function (i, elementId) {
                var tempData = pageBean.findData("id", elementId);
                if (tempData != null) {
                    pageBean.delOne(tempData)
                }
            })
            return pageBean.getSource();
        },


        doMaskImage: function (showImageId) {
            VODNew.MaskManager.startWork(showImageId);
        },

        loadImageOver: function (element) {
            // 1280 ,760
            var bounds = VODNew.Config.CropInstance.getBounds();
            console.log("loadImageOver", element.x, element.y, element.width, element.height);
            VODNew.Config.originalImageSize.width = bounds[0];
            VODNew.Config.originalImageSize.height = bounds[1];
            $("#ocr_image_div").css("width", bounds[0] > VODNew.Config.originalImageSize.limitWidth ? VODNew.Config.originalImageSize.limitWidth + 15 : bounds[0] + 15);
            $("#ocr_image_div").css("height", bounds[1] > VODNew.Config.originalImageSize.limitHeight ? VODNew.Config.originalImageSize.limitHeight + 15 : bounds[1] + 15);
        },
        loadImageOver3: function (element) {
            $("#demoImg").show();
            console.log("loadImageOver3", element.x, element.y, element.width, element.height);
            $("#demoImgDiv").css("width", element.naturalWidth);
            $("#demoImgDiv").css("height", element.naturalHeight)
        },
        logSubmit: function (type, params, response, plusMsg) {
            var submitLogData = {
                channelId: VODNew.Dao.getParamsData()._channel_id,
                type: type,
                descr: JSON.stringify(response) + ( plusMsg == null ? "" : "|" + plusMsg) + "|" + JSON.stringify(params) };
            VODNew.Util.doSubmitLogEntity(submitLogData);

        },
        episodeLogSubmit: function (programId, type, params, response, plusMsg) {
            var submitData = {
                programId: programId,
                type: type,
                user: auth.baseInfo.authInfo.email,
                descr: JSON.stringify(response) + ( plusMsg == null ? "" : "|" + plusMsg) + "|" + JSON.stringify(params) };
            VODNew.Util.doSubmitEpisodeLogEntity(submitData);
            if (VODNew.Config.VOD_LOG_TYPE.sendProgramDataToLego == type) {
                var tempData = {
                    success: true,
                    funcType: "create_video",
                    sendData: JSON.stringify(params),
                    plusMsg: plusMsg,
                    response: response,
                    programId: programId,
                    serverIp: VODNew.Dao.getParamsData().ip,
                    paramType: VODNew.Util.isAppendFragmentMode() ? EpgWeb.PingBack.PARAM_TYPE.append_submit : EpgWeb.PingBack.PARAM_TYPE.normal_submit
                }
                EpgWeb.PingBack.doQuickSend(tempData);
                tempData = null;
            } else if (VODNew.Config.VOD_LOG_TYPE.submitDotData == type) {
                if (VODNew.Util.isAppendFragmentMode() && 1 === params.tag) {
                    var isSuc = response != null && response.error == 0;
                    EpgWeb.PingBack.doQuickSend({
                        paramType: EpgWeb.PingBack.PARAM_TYPE.append_submit,
                        success: isSuc,
                        funcType: "submit_format",
                        sendData: JSON.stringify(params),
                        plusMsg: plusMsg,
                        response: response,
                        programId: programId,
                        serverIp: VODNew.Dao.getParamsData().ip })
                }
            }
        },
        doSubmitLogEntity: function (submitLogData) {
            VODNew.Dao.submitLogEntity(submitLogData, function (data) {
                    if (data == null || data.code != "A00000") {
                        console.warn("submitLogEntity error");
                    } else {
                        console.log("submitLogEntity suc");
                    }
                }
            )
        },
        doSubmitEpisodeLogEntity: function (submitLogData) {
            VODNew.Dao.submitEpisodeLogEntity(submitLogData, function (data) {
                    if (data == null || data.code != "A00000") {
                        console.warn("SubmitEpisodeLogEntity error");
                    } else {
                        console.log("SubmitEpisodeLogEntity suc");
                    }
                }
            )
        },
        fillDefaultTitle: function () {
            var settings = VODNew.Dao.settings;
            var c_sTime = $('input[name=eTime]').val();
            var s_sTime = $('input[name=sTime]').val();
            if (s_sTime == '' && isNaN(s_sTime)) {
                return
            }
            if (c_sTime != '' && !isNaN(c_sTime)) {
                if ($("input[name=videoName]").val().length > 0) {
                    return;
                }
                if ($('input[name=videotype]:checked').val() == -1) {
                    var show = settings.taskid + '-' + VODNew.Dao.getParamsData().channel_name + '-' + settings.today + '-' + s_sTime + '-' + c_sTime;
                    $('input[name=videoName]').val(show);
                    var ocrFirstTitle = VODNew.Util.binSearchOcrTitle(s_sTime, c_sTime).shift();
                    if (ocrFirstTitle) {
                        $("input[name=videoName]").val(ocrFirstTitle);
                        $("input[name=videoName]").attr("eut", encodeURIComponent(ocrFirstTitle));
                        $("input[name=videoName]").change()
                    }
                }
            }
        },
        doSt1Data: function (delAdStr, options, dadianmerge) {
            var global = VODNew.Config.Global;
            var paramsData = VODNew.Dao.getParamsData();
//////////////////////////制作数据统计///////////////////////////////////////////
            var sSrc = $("#img-" + options.sTime).attr("src"),
                eSrc = $("#img-" + options.eTime).attr("src");
            var s_fp_time = sSrc.substr(VODNew.Config.Global.fp_pos, 10);
            var e_fp_time = eSrc.substr(VODNew.Config.Global.fp_pos, 10);
            var seconds = (parseInt(e_fp_time) - parseInt(s_fp_time));
            options.seconds = seconds;
            $.each(global.d_sty2Data, function (n, adData) {
                var adStartTime = adData.sTime, adEndTime = adData.eTime;
                if (options.sTime < adStartTime && options.eTime > adEndTime) {

                    var sSrc = $("#img-" + adStartTime).attr("src"),
                        ads_fp_pos = sSrc.lastIndexOf('/') + 1,
                        ads_fp_time = sSrc.substr(ads_fp_pos, 10),
                        eSrc = $("#img-" + adEndTime).attr("src"),
                        ade_fp_pos = eSrc.lastIndexOf('/') + 1,
                        ade_fp_time = eSrc.substr(ade_fp_pos, 10);
                    var ad_seconds = (parseInt(ade_fp_time) - parseInt(ads_fp_time));
                    seconds = seconds - ad_seconds;
                }
            });


            VODNew.Util.dl_click("/api/st?bs=1&st=1&prid=" + options.programId
                    + "&pr_name=" + encodeURIComponent(options.title)
                    + "&pr_mins=" + seconds
                    + "&cname=" + options.cname
                    + "&u=" + VODNew.Util.getUserName()
                    + "&cp=" + paramsData._channel_name_str
                    + "&bt=" + new Date(parseInt(s_fp_time) * 1000).format("yyyy-MM-dd hh:mm:ss")
                    + "&et=" + new Date(parseInt(e_fp_time) * 1000).format("yyyy-MM-dd hh:mm:ss")
                    + "&dst=" + new Date().format("yyyy-MM-dd hh:mm:ss")
                    + "&ablum_name=" + options.album
                    + "&s_a_dot=" + ""                   //广告开始
                    + "&s_m_dot=" + options.sTime					//打点手动开始
                    + "&e_a_dot=" + ""						//广告结束
                    + "&e_m_dot=" + options.eTime					//打点手动结束
                    + "&ad_info=" + delAdStr
                    // 2017-05-02 tag dadianmerge add start
                    + "&ocr_flag=" + dadianmerge.ocr_flag
                    + "&intelligent_insert_time=" + dadianmerge.intelligent_insert_time
                    + "&ocr_title_flag=" + VODNew.Config.OCR_TITLE_FLAG
                // 2017-05-02 tag dadianmerge add end
            );
            VODNew.Config.FIRST_FRAGMENT_START = null;
            VODCom.AutoTitle.doPostEpgAutoTitleData({
                programId: options.programId,
                channelName: paramsData._channel_name_str,
                title: options.title,
                begin: new Date(parseInt(s_fp_time) * 1000).format("yyyy-MM-dd hh:mm:ss"),
                end: new Date(parseInt(e_fp_time) * 1000).format("yyyy-MM-dd hh:mm:ss")
            })
            VODNew.Util.doPostEpgOcrData(
                {
                    programId: options.programId,
                    channelName: paramsData._channel_name_str,
                    title: options.title,
                    begin: new Date(parseInt(s_fp_time) * 1000).format("yyyy-MM-dd hh:mm:ss"),
                    end: new Date(parseInt(e_fp_time) * 1000).format("yyyy-MM-dd hh:mm:ss"),
                    ocrFlag: dadianmerge.ocr_flag
                }
            );
        },
        doSt2Data: function (options) {
            var global = VODNew.Config.Global;
            var paramsData = VODNew.Dao.getParamsData();
            //////////////////////////长视频智能分析统计///////////////////////////////////////////

// sty2Data 缓存sty2数据
// d_sty2Data 缓存提交后的广告头和尾

            var headerCompleteNumbers = headerIncompleteNumbers = headerFaultNumbers = 0,
                lastCompleteNumbers = lastIncompleteNumbers = lastFaultNumbers = 0,
                adCompleteNumbers = adIncompleteNumbers = adFaultNumbers = 0;

// 计算广告智能分析正确数
            var eq_sTime, eq_eTime,
                headerSty2Index, headerSty2Length, headerListIndex,
                lastSty2Index, lastSty2Length, lastListIndex,
                gtSty2Flag, ltSty2Flag;
            var sty2DataList = global.sty2Data.list;
            if (global.channelInfo.length == 0 || global.channelInfo[0].sty2 == 1) {

                $.each(global.d_sty2Data, function (n, adData) {
                    var sVid = $('.' + adData.sTime + '-jump').attr("id").split("-")[1],
                        eVid = $('.' + adData.eTime + '-jump').attr("id").split("-")[1];
                    console.log("sty2DataList ,length ", sty2DataList.length);
                    $.each(sty2DataList, function (i, item) {
                        console.log("itemvideo_list ,length ", (item.video_list == null), item.video_list.length);
                        $.each(item.video_list, function (j, sty2Id) {
                            if (item.type == VODNew.Config.adLib) {
                                var length = item.video_list.length;
                                if (sVid == sty2Id) {
                                    headerSty2Index = i;
                                    headerListIndex = j;
                                    headerSty2Length = length;
                                    eq_sTime = sty2Id;
                                } else if (eVid == sty2Id) {
                                    lastSty2Index = i;
                                    lastListIndex = j;
                                    lastSty2Length = length;
                                    eq_eTime = sty2Id;
                                }
                                if (j == 0 && sVid < sty2Id) {
                                    ltSty2Flag = true;
                                }
                                if (j == length - 1 && eVid > sty2Id) {
                                    gtSty2Flag = true;
                                }
                            }
                        });
                    });


                    if (eq_sTime == null && eq_eTime == null) {
                        if (ltSty2Flag && gtSty2Flag) {
                            adIncompleteNumbers++;
                        } else {
                            adFaultNumbers++;
                        }

                    } else if (eq_sTime == null || eq_eTime == null) {
                        adIncompleteNumbers++;
                    } else if (eq_sTime != null && eq_eTime != null) {
                        var adRound = eq_eTime - eq_sTime + 1;
                        if (headerSty2Index == lastSty2Index && adRound == headerSty2Length) {
                            adCompleteNumbers++;
                        } else if (headerSty2Index == lastSty2Index && adRound != headerSty2Length) {

                            adIncompleteNumbers++;
                        } else if (headerSty2Index != lastSty2Index) {
                            if (headerListIndex != 0 || lastListIndex != lastSty2Length - 1) {
                                adIncompleteNumbers++;
                            } else {
                                var index = headerSty2Index;
                                var flag = true;
                                while (flag) {
                                    if (index == lastSty2Index) {
                                        adCompleteNumbers++;
                                        flag = false;
                                    } else {
                                        var videoList = sty2DataList[index].video_list;
                                        var nextVideoList = sty2DataList[index + 1].video_list;
                                        if ((nextVideoList[0] - videoList[videoList.lenth - 1]) >= 2) {
                                            adIncompleteNumbers++;
                                            flag = false;
                                        }
                                    }
                                    index++;
                                }
                            }
                        }
                    }

                });
// 广告智能分析提交数请空
                global.d_sty2Data = [];
                headerSty2Index = null;
                eq_sTime = null;
                eq_eTime = null;

                sVid = $('.' + options.sTime + '-jump').attr("id").split("-")[1];
                eVid = $('.' + options.eTime + '-jump').attr("id").split("-")[1];
// 计算片头和片尾正确数
                console.log("sty2DataList ,length ", sty2DataList.length);
                $.each(sty2DataList, function (i, item) {
                    console.log("itemvideo_list ,length ", (item.video_list == null), item.video_list.length);
                    $.each(item.video_list, function (j, sty2Id) {
                        if (item.type == VODNew.Config.adLibHead) {
                            if (sVid == sty2Id) {
                                headerSty2Index = j;
                                eq_sTime = sty2Id;
                            }
                        }
                        if (item.type == VODNew.Config.adLibTail) {
                            if (eVid == sty2Id) {
                                lastSty2Index = j;
                                lastSty2Length = item.video_list.length;
                                eq_eTime = sty2Id;
                            }
                        }
                    });
                });

                if (eq_sTime == null) {
                    headerFaultNumbers++;
                } else if (eq_sTime != null && headerSty2Index == 0) {
                    headerCompleteNumbers++;
                } else {
                    headerIncompleteNumbers++;
                }

                if (eq_eTime == null) {
                    lastFaultNumbers++;
                } else if (eq_eTime != null && lastSty2Index == lastSty2Length - 1) {
                    lastCompleteNumbers++;
                } else {
                    lastIncompleteNumbers++;
                }

                VODNew.Util.dl_click("/api/st?bs=1&st=2&channelId=" + paramsData._channel_id
                        + "&channelName=" + paramsData._channel_name_str
                        + "&channelCode=" + paramsData.channel_name
                        + "&programId=" + options.programId
                        + "&programName=" + encodeURIComponent(options.title)
                        + "&categoryName=" + options.cname
                        + "&albumName=" + options.album
                        + "&programTime=" + options.seconds
                        + "&headerCompleteNumbers=" + headerCompleteNumbers
                        + "&headerIncompleteNumbers=" + headerIncompleteNumbers
                        + "&headerFaultNumbers=" + headerFaultNumbers
                        + "&lastCompleteNumbers=" + lastCompleteNumbers
                        + "&lastIncompleteNumbers=" + lastIncompleteNumbers
                        + "&lastFaultNumbers=" + lastFaultNumbers
                        + "&adCompleteNumbers=" + adCompleteNumbers
                        + "&adIncompleteNumbers=" + adIncompleteNumbers
                        + "&adFaultNumbers=" + adFaultNumbers
                        + "&user=" + VODNew.Util.getUserName()
                );
            }
/////////////////////////////end//////////////////////////////////////////////////////
        },
        //////////////////////分片提交相关 开始//////////////////////////////////
        checkChangeFragmentMode: function () {
            var sTime = $('input[name=sTime]').val();
            if (!VODNew.Plugin.Validate.checkNum(sTime)) {
                VODNew.Plugin.tips("error", "分片的起点 必须为数字")
                return false;
            }
            var cname = $('input[name=categoryName]').val();
            var videotype = $('input[name=videotype]:checked').val();
            var title = $('input[name=videoName]').val();
            if (videotype == 0 || videotype == 1) {
                var bind_sel_name = $('input[name=videoName]').attr("bind-sel-name");
                if (bind_sel_name == null || bind_sel_name == "" || title != bind_sel_name) {
                    VODNew.Plugin.tips("error", "标题数据异常")
                    return false;
                }
            } else if (videotype == -1) {
                if (title.length == 0) {
                    VODNew.Plugin.tips("error", "标题未输入")
                    return false
                }
                var bind_sel_name = $('input[name=categoryName]').attr("bind-sel-name");
                if (bind_sel_name == null || bind_sel_name == "" || cname != bind_sel_name) {
                    VODNew.Plugin.tips("error", "频道 数据异常")
                    return false;
                }
            }
            return true;
        },

        addToDivFragment: function (currentNum) {
            if (currentNum == null) {
                currentNum = $("#div_fragment_append").children().length + 1;
            }
            if (currentNum == 2) {
                $('input[name=isAppendFragment]').attr("disabled", "disabled");
            }
            var htmlArr = [];
            htmlArr.push('<div fragment-line="0" >');
            htmlArr.push(' 分片起点：<input type="text" class="form-control input-sm" style="width:55px" readonly="true" > &nbsp; &nbsp;');
            htmlArr.push(' 分片终点：<input type="text"  class="form-control input-sm" style="width:55px">');
            htmlArr.push('  <button type="button" name="btn_preview_fragment" class="btn btn-primary ">预览分片</button>');
            htmlArr.push('  <button type="button" name="btn_submit_fragment" class="btn btn-primary ">提交分片</button>');
            htmlArr.push('  </div>');
            var divTarget = $(htmlArr.join(""));
            divTarget.attr("fragment-line", currentNum);
            if (currentNum == 1) {
                divTarget.find("input:eq(0)").val($('input[name=sTime]').val());
                divTarget.appendTo($("#div_fragment_append"));
            } else {
                var preDivTarget = $("div[fragment-line=" + (currentNum - 1) + "]");
                var etVal = preDivTarget.find("input:eq(1)").val();
                if (!VODNew.Plugin.Validate.checkNum(etVal)) {
                    return;
                }
                var stVal = parseInt(preDivTarget.find("input:eq(0)").val());
                if (stVal >= etVal) {
                    return;
                }
                preDivTarget.find("input:eq(1)").attr("readonly", true);
                divTarget.find("input:eq(0)").val(parseInt(etVal) + 1);
                divTarget.appendTo($("#div_fragment_append"));
            }
        },
        doQuickFragmentSubmit: function () {
            var childLength = $("#div_fragment_append").children().length;
            if (childLength == 1) {
                return;
            }
            var parentDiv = $("div[fragment-line='" + (childLength - 1) + "']");
            VODNew.Util.handlerRemoveFgRemindBlock();
            VODNew.Util.doFragmentSubmit(parentDiv, {
                doSuc: function () {
                    console.log("doQuickFragmentSubmit suc ")
                },
                doError: function () {
                    console.log("doQuickFragmentSubmit error ")
                },
                doRevert: function () {
                    console.log("doQuickFragmentSubmit doRevert ")
                }
            })
        },
        doShortcutFragmentSubmit: function () {
            if ($("#fragment-dlg").is(":visible")) {
                return;
            }
            var btn = $("button[name=btn_submit_fragment]:visible");
            if (btn.length == 1) {
                btn.click();
            }
        },
        doShortcutSetFragmentEnd: function () {
            if ($("#fragment-dlg").is(":visible")) {
                return;
            }
            var btn = $("button[name=btn_submit_fragment]:visible");
            if (btn.length != 1) {
                VODNew.Plugin.tips("error", "尚未启用分片！");
                return;
            }
            btn.parent().find("input:eq(1)").val($.trim($(".red").parent().find(".pid").html()));
        },
        doFragmentSubmit: function (parentDiv, callhandler) {
            var settings = VODNew.Dao.settings;
            var paramsData = VODNew.Dao.getParamsData();
            if (settings.taskid < 1.) {
                callhandler.doError('任务ID为空,不能提交!');
                return;
            }
            if ($("span[span-mode=warn]").is(":visible")) {
                callhandler.doError('标题过长,不能提交!');
                return;
            }
            $('input[name=imageId]').val($('input[name=imageId]').val().trim());

            var sTime = $("#cForm").find("input[name=sTime]").val()
            var eTime = parentDiv.find("input:eq(1)").val();
            var pic = sTime;
            var fantasyTitle = $('input[name=fantasyTitle]').val() ? $('input[name=fantasyTitle]').val() : "";
            var title = $('input[name=videoName]').val(),
                channel = $('input[name=categoryName]').suggest("getValue");
            var data = {
                '起始帧': sTime,
                '结束帧': eTime,
                '标题': title,
                '频道': channel
            }
            var album = $('input[name=albumName]').val();
            var cpOption = $('#cp').children('option:selected');
            var priority = $('input[name=priority]:checked').val(), //优先级
                video_dpi = $('input[name=video_dpi]:checked').val(), //分辨率
                isVolumeStandard = $('input[name=isVolumeStandard]:checked').val(), //节目音量标准化参数
                isVolumeStandardForMaterial = $('input[name=isVolumeStandardForMaterial]:checked').val(), //素材音量标准化参数
                uid = cpOption.attr("uid"), //表示ugc用户id
                partnerId = cpOption.attr("partnerId"), //表示合作方id
                episodeType = cpOption.attr("episodeType"); //取值为0或1,1表示为ugc视频，0为普通ppc视频
            uid = !uid ? "" : uid;
            partnerId = !partnerId ? "" : partnerId;
            episodeType = !episodeType ? "" : episodeType;
            var albumId = '';
            if (album) {
                albumId = $('input[name=albumName]').suggest("getValue") || "";
            }
            if (!this.checkStAndEt(sTime, eTime)) {
                callhandler.doError("开始结束时间错误", true);
                return;
            }
            var checkArr = [];
            var numTime = $('#picNum').text();
            checkArr.push({value: parseInt(eTime), error: "结束帧不存在,不能提交", type: "lt", other: parseInt(numTime)  })
            if (!VODNew.Plugin.Validate.batchCheck(checkArr)) {
                callhandler.doError("interrupt checkLiveType checkRepeat", true);
                return;
            }
            $('#addInfo').attr('disabled', 'disabled');
            if (!this.validAddInfo(data)) {
                callhandler.doError("validAddInfo 失败", true);
                return;
            }
            VODCom.Player.splitData(sTime, eTime, true);
            if (!settings.subData.length) {
                //alert('该条打了删除，不能再打拆条!');
                callhandler.doError('该条打了删除，不能再打拆条!');
                return;
            }
            var p_vid = $('input[name=videoName]').suggest("getValue") || 0;
            var p_albumId = $('input[name=albumName]').suggest("getValue") || "";
            var videotype = $('input[name=videotype]:checked').val();
            if (videotype == -1) {
                p_vid = 0
            }
            var dataJson = {
                'videoId': p_vid,
                'priority': priority,
                'albumName': album,
                'videoName': title,
                'categoryId': channel,
                'albumId': p_albumId,
                'reTranscodeConfirm': VODNew.Util.getReTranscodeConfirmVal(),
                'freeType': paramsData.freeType,
                'isVolumeStandard': isVolumeStandard,
                isVolumeStandardForMaterial: isVolumeStandardForMaterial,
                userArea: VODNew.Util.getUserRegion()
            };
            if ($("#locationDiv").is(":visible")) {
                dataJson.locationCategory = $("input[name=location]").suggest("getValue");
            }
            if (videotype == -1) {
                dataJson.fantasyTitle = fantasyTitle;
            }

            var newPA = {
                title: title,
                cat: channel,
                alb: albumId,
                enableClound: VODNew.Util.getEnableCloundVal(),
                priority: priority,
                video_dpi: video_dpi,
                uid: uid,
                partnerId: partnerId,
                episodeType: episodeType
            }
            if (videotype == -1) {
                newPA.fantasyTitle = fantasyTitle;
            } else if (videotype == 1) {
                newPA.reTranscodeConfirm = VODNew.Util.getReTranscodeConfirmVal();
            }
            var dealRoute = -1;
            if (VODNew.Config.lastLegoSubmitObj.programId != VODNew.Config.fragmentPid) {
                VODNew.Config.lastLegoSubmitObj.programId = VODNew.Config.fragmentPid;
                VODNew.Config.lastLegoSubmitObj.hasSubmit = false;
                dealRoute = 1;
            } else if (VODNew.Config.lastLegoSubmitObj.hasSubmit == false) {
                dealRoute = 2;
            } else {
                dealRoute = 3;
            }
            if (VODNew.Config.FIRST_FRAGMENT_START == null) {
                VODNew.Config.FIRST_FRAGMENT_START = this.formatDateTimeFormat(new Date());
            }
            if (dealRoute == 1 || dealRoute == 2) {
                var sendData = {"request": JSON.stringify({url: VODNew.Constant.thirdUrl_peditor_submit, type: "post", params: {
                    data: JSON.stringify(dataJson)
                }, needCookie: true}), timeSign: new Date().getTime()}
                VODNew.Dao.dopeditorSubmit(sendData, {
                    doSuc: function (res) {
                        if (res == null || res.code != 'A00000') {
                            VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.sendProgramDataToLego, sendData, res, "fromUrl:" + VODNew.Constant.thirdUrl_peditor_submit);
                            VODNew.Plugin.tips("error", res == null ? "lego接口无效返回值" : "lego错误：" + res.msg);
                            callhandler.doRevert();
                        } else {
                            var programId = res.data.programId;
                            if (!programId) {
                                VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.sendProgramDataToLego, sendData, {error: '乐高返回的programId为空!'}, "fromUrl:" + VODNew.Constant.thirdUrl_peditor_submit);
                                callhandler.doError('乐高返回的programId为空!');
                                return;
                            }
                            VODNew.Util.episodeLogSubmit(programId, VODNew.Config.VOD_LOG_TYPE.sendProgramDataToLego, sendData, res, "fromUrl:" + VODNew.Constant.thirdUrl_peditor_submit);
                            VODNew.Config.fragmentPid = programId;
                            VODNew.Config.lastLegoSubmitObj.programId = VODNew.Config.fragmentPid;
                            VODNew.Config.lastLegoSubmitObj.hasSubmit = true;
                            //提交数据给刘之红
                            VODNew.Util.postFragmentData(settings.subData, newPA, pic, VODNew.Config.fragmentPid, callhandler)
                        }
                    },
                    doError: function (XMLHttpRequest, status) {
                        VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.sendProgramDataToLego, sendData, { type: "error reqeust", status: status }, "fromUrl:" + VODNew.Constant.thirdUrl_peditor_submit);
                        callhandler.doError('网络错误,请稍后再提交！');
                        return;
                        //              VODNew.Plugin.tips("error", '接口/peditor/submit调用超时10秒未响应！请联系乐高相关负责人员！');
                    }
                })
            } else if (dealRoute == 3) {
                //提交数据给刘之红
                VODNew.Util.postFragmentData(settings.subData, newPA, pic, VODNew.Config.fragmentPid, callhandler)
            }

        },
        transToFragmentMode: function () {
            $('input[name=videotype]').attr("disabled", "disabled");
            $('input[name=sTime]').attr("readonly", true);
            $('input[name=categoryName]').attr("disabled", "disabled");
            $('input[name=videoName]').attr("readonly", true);
            $('input[name=albumName]').attr("readonly", true);
            $('input[name=location]').attr("readonly", true);
            $("#cp").attr("readonly", true);

            $('input[name=priority]').attr("disabled", "disabled")
            $('input[name=video_dpi]').attr("disabled", "disabled")
            $('input[name=isVolumeStandard]').attr("disabled", "disabled");
            $('input[name=needRemakeVideo]').attr("disabled", "disabled");
            $('input[name=isVolumeStandardForMaterial]').attr("disabled", "disabled");

            $('input[name=reTranscodeConfirm]').attr("disabled", "disabled");
            $("#div_fragment_append").html("");
            $("#div_fragment_append").show();
            VODNew.Util.handlerChangeFgRemindStart()
            VODNew.Util.addToDivFragment(1);

        },

        transToNormalMode: function () {
            VODNew.Config.fgRemindObj.stop = true;
            $('input[name=videotype]').removeAttr("disabled");
            $('input[name=sTime]').removeAttr("readonly");
            $('input[name=videoName]').removeAttr("readonly");
            $('input[name=albumName]').removeAttr("readonly");
            $('input[name=location]').removeAttr("readonly");
            $("#cp").removeAttr("readonly");
            $('input[name=priority]').removeAttr("disabled");
            $('input[name=video_dpi]').removeAttr("disabled");
            $('input[name=isVolumeStandard]').removeAttr("disabled");
            $('input[name=needRemakeVideo]').removeAttr("disabled");
            $('input[name=isVolumeStandardForMaterial]').removeAttr("disabled");
            $('input[name=isAppendFragment]').removeAttr("disabled");
            $('input[name=reTranscodeConfirm]').removeAttr("disabled");
            var videotype = $('input[name=videotype]:checked').val();
            if (videotype == -1) {
                $('input[name=categoryName]').removeAttr("disabled");
            }
            $("#div_fragment_append").hide();
        },
        postFragmentData: function (list, newPA, imageId, programId, callhandler) {
            var sList = '[' + list.join(",") + "]";
            var paramsData = VODNew.Dao.getParamsData();
            var settings = VODNew.Dao.settings;
            var dotData = VODNew.Dao.getDotData();
            var accurateFrame = VODNew.AccurateFrame.getAccurateFrame()
            var pData = {
                tag: 0,
                'title': newPA.title,
                'categoryId': newPA.cat,
                'albumId': newPA.alb,
                'code': paramsData.channel_name,
                'programId': programId,
                'userId': VODNew.Util.getUserId() + "",
                'from_client': true,
                'key': settings.taskid,
                'list': sList,
                'imageId': imageId,
                'head': accurateFrame.head,
                'end': "",
                'priority': newPA.priority,
                'video_dpi': newPA.video_dpi,
                'uid': newPA.uid,
                'partnerId': newPA.partnerId,
                'episodeType': newPA.episodeType,
                'enableClound': newPA.enableClound,
                'needRemakeVideo': VODNew.Util.getNeedRemakeVideo(),
                'delogoArr': JSON.stringify(VODNew.Util.fetchDelogoArr(list))
            };
            if ("fantasyTitle" in newPA) {
                pData.fantasyTitle = newPA.fantasyTitle;
            }
            if ("reTranscodeConfirm" in newPA) {
                if (VODNew.Config.lastSubmitObj.programId != programId || VODNew.Config.lastSubmitObj.hasSubmit == false) {
                    VODNew.Config.lastSubmitObj.programId = programId;
                    VODNew.Config.lastSubmitObj.hasSubmit = true;
                    pData.reTranscodeConfirm = newPA.reTranscodeConfirm;
                }
            }

            VODNew.Dao.postSync(dotData.appendUrl, pData, {
                doSuc: function (data) {
                    console.log(" 日志:" + JSON.stringify(pData))
                    //        VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.submitFragmentData, pData, data, "url:" + dotData.appendUrl);
                    VODNew.Util.episodeLogSubmit(programId, VODNew.Config.VOD_LOG_TYPE.submitFragmentData, pData, data, "url:" + dotData.appendUrl);
                    if (data.error != 0) {
                        callhandler.doError(data.error);
                    } else {
                        callhandler.doSuc();
                        VODNew.Plugin.tips("success", '提交分片成功');
                    }
                },
                doError: function () {
                    VODNew.Util.episodeLogSubmit(programId, VODNew.Config.VOD_LOG_TYPE.submitFragmentData, pData, {type: "request error"}, "url:" + dotData.appendUrl);
                    //       VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.submitFragmentData, pData, {type: "request error"}, "url:" + dotData.appendUrl);
                    callhandler.doError('编码服务器网络错误,请稍后再提交！');
                }
            }, false)
        },
        isAppendFragmentMode: function () {
            return $("input[name=isAppendFragment][value='1']").is(":checked")
        },
        checkFragmentEnd: function (eTime) {
            var childLength = $("#div_fragment_append").children().length;
            if (childLength == 1) {
                return true;
            }
            var fragmentEnd = $("div[fragment-line='" + (childLength - 1) + "']").find("input:eq(1)").val();
            if (parseInt(fragmentEnd) > parseInt(eTime)) {
                VODNew.Plugin.tips("error", "结尾帧不能小于分片结尾帧！");
                return false;
            }
            return true;
        },
        autoFillFragmentEnd: function () {
            var autoEnd = parseInt($("#fragment-dlg").find("span:eq(1)").html());
            var childLength = $("#div_fragment_append").children().length;
            $("div[fragment-line='" + childLength + "']").find("input:eq(1)").val(autoEnd);
            VODNew.Config.AUTO_SUBMIT_TRIGGER = true;
            $("div[fragment-line='" + childLength + "']").find("button[name=btn_submit_fragment]").click();
        },
        handlerRemoveFgRemindBlock: function () {
            VODNew.Config.fgRemindObj.lastTime = Date.now() + 100;
            VODNew.Config.fgRemindObj.block = false;
        },
        handlerChangeFgRemindStart: function () {
            VODNew.Config.fgRemindObj.lastTime = Date.now() + 100;
            VODNew.Config.fgRemindObj.stop = false;
        },
        //////////////////////分片提交相关 结束//////////////////////////////////

        //广告，打点片段 联动相关 开始///////////////////////
        checkAdvertAffectDot: function (st, et) {
            var childLength = $("#div_fragment_append").children().length;
            if (childLength > 1) {
                var sTime = $("#cForm").find("input[name=sTime]").val()
                var fragmentEnd = $("div[fragment-line='" + (childLength - 1) + "']").find("input:eq(1)").val();
                var intValue_d_sTime = parseInt(st);
                var intValue_d_eTime = parseInt(et);
                var intValue_sTime = parseInt(sTime);
                var intValue_fragmentEnd = parseInt(fragmentEnd);
                if (( intValue_d_sTime <= intValue_fragmentEnd && intValue_d_sTime >= intValue_sTime ) ||
                    ( intValue_d_eTime <= intValue_fragmentEnd && intValue_d_eTime >= intValue_sTime )) {
                    return true;
                }
            }
            return false
        },
        //广告，打点片段 联动相关 结束///////////////////////
        doPostEpgOcrData: function (baseObj) {
            if (VODNew.Config.OCR_TITLE_FLAG == 1) {
                var sendData = VODNew.Util.prepareOcr2Data(baseObj);
                VODNew.Dao.postOcr2Data({data: JSON.stringify(sendData) }, function (data) {
                    if (data != null && data.code == "A00000") {
                        VODNew.Plugin.tips("success", '投递epg ocr 数据成功');
                    } else {
                        VODNew.Plugin.tips("error", '投递epg ocr 数据失败');
                    }
                });
            }
            VODNew.Config.OCR_TITLE_FLAG = 0;
            VODNew.Config.OCR_TITLE_ORIGIN = null;
        },
        prepareOcr2Data: function (baseObj) {
            var data = {
                channelName: baseObj.channelName,
                ocrTitle: VODNew.Config.OCR_TITLE_ORIGIN.trim(),
                ocrTitleCharLen: 0,
                addTime: VODNew.Util.formatDateTimeFormat(new Date()),
                liveBeginTime: baseObj.begin,
                liveEndTime: baseObj.end,
                ocrFlag: baseObj.ocrFlag,
                user: VODNew.Util.getUserName(),
                imageUrl: $("#ocr_image").attr("src"),
                locations: $("input[name=image_location]").val(),
                userTitle: baseObj.title.trim(),
                userTitleCharLen: 0,
                legoProgramId: baseObj.programId,
                percent: 0
            };
            data.ocrTitleCharLen = Com.string.getStrLength(data.ocrTitle);
            data.userTitleCharLen = Com.string.getStrLength(baseObj.title);
            data.percent = VODCom.OCR.accountOcrPercent(data.ocrTitle, data.userTitle);
            return data;
        },

        updateGridMaskEntityRow: function (object) {
            if (object != null) {
                var findData = VODNew.Config.PageBeanMaskEntity.findData("index", object.index);
                for (var key in object) {
                    if (key != "index" && findData.hasOwnProperty(key)) {
                        findData[key] = object[key];
                    }
                }
                $('#mask_list').setRowData(object.index, object);
            }
        },
        notifyAlert: function (msg) {
            var sendData = {};
            sendData.user = auth.dev() ? VODNew.Config.ALERT_USER.TEST_SEND : VODNew.Config.ALERT_USER.PRO_SEND;
            sendData.content = msg;
            //     sendData.email_subject可以自定义邮件标题
            sendData.notifyType = VODNew.Config.ALERT_PLATFORM_NOTIFY.SEND_CHAT;
            EpgWeb.Util.notifyAlert(sendData, function (rdata) {
                console.log("notifyAlert:" + JSON.stringify(rdata))
            })
        },
        checkAdvertSupport: function () {
            VODNew.Dao.doAdvertTest(function (returnData) {
                if (returnData != null) {
                    if (returnData.statusText == "error") {
                        return;
                    }
                    VODNew.Config.ADVERT_SUPPORT = true;
                }
            });
        },
        //灰度上线
        checkGreyMode: function () {
            if (VODNew.Config.GREY_MODE.containsObj({ip: VODNew.Dao.getParamsData().ip, cn: VODNew.Dao.getParamsData()._channel_name_str})) {
                $("button[name=btn_get_auto_title]").show();
                VODNew.Config.HELP_DATA.push(VODNew.Config.HELP_DATA_AUTO_TITLE[0] );
            } else {
                $("button[name=btn_get_auto_title]").hide();
            }
        },
        getUserRegion: function () {
            var retRegion = "";
            var region = auth.baseInfo.authInfo.region;
            var checkArr = ["","bj","sh","cq","tw"];
            if(region > 0 && region <  checkArr.length ){
                retRegion = checkArr[region];
            }else{
                return "";
            }
            return retRegion
        },
        getNeedRemakeVideo: function () {
            return  parseInt($('input[name=needRemakeVideo]:checked').val());
        }
    })
})
;
define(
    '../vodnew/VODNew.Plugin',['require','exports','module'],function (require, exports, module) {
        VODNew.Plugin = $.extend(true, {}, EpgWeb.Plugin, {
            tips: (function () {
                var str = '<div class="alert alert-dismissible" role="alert1" style="display: inline;text-align: center;width: 420px">'
                    + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'
                    + '<span id="tips">{{cnt}}</span><strong style="margin-right:30px;">【3秒后自动关闭】</strong>'
                    + '</div>';
                var _timeId = null;

                return function (func, content) {
                    //移除旧对象
                    $("div[role=alert1]").remove();
                    if (_timeId) {
                        clearTimeout(_timeId);
                    }
                    var html = str;
                    html = html.replace(/{{cnt}}/g, content);
                    $(html).appendTo($(document.body));
                    //重新获取
                    var targetElement = $("div[role=alert1]");
                    targetElement.css("left", $(document.body).width() / 2 - $("div[role=alert1]").width() / 2);

                    if (func !== undefined) {
                        if (func == "success") {
                            targetElement.removeClass("alert-danger");
                            targetElement.addClass("alert-success");
                        }
                        else if (func == "error") {
                            targetElement.removeClass("alert-success");
                            targetElement.addClass("alert-danger");
                        }

                        _timeId = setTimeout(function(){
                            $('div[role=alert1]').find("button").trigger("click");
                        }, 3000);
                    }
                    else {
                        console.log("func is not exists!");
                    }
                };
            })()

        })
        VODNew.Plugin.Validate.bindDefaultHandler( function(msg){
            VODNew.Plugin.tips("error", msg);
        } );
    }
);
define(
    '../vodnew/VODNew.Evt',['require','exports','module'],function (require, exports, module) {
        VODNew.Evt = {
            InitBindEvt: function () {
                // 显示小窗口视频预览
                var playOneInfo = VODNew.Dao.playOneInfo;
                $("#makedImg").on("mouseenter mouseleave", "img", function (event) {
                    var self = $(this);
                    if (event.type == 'mouseenter') {
                        playOneInfo.mouseenter = true;
                        playOneInfo.left = self.offset().left - $("#play-one").width();
                        playOneInfo.top = self.offset().top;
                        playOneInfo.time = self.attr("id").split("-")[1];
                    } else if (event.type == 'mouseleave') {
                        playOneInfo.mouseenter = false;
                        $("#play-one").hide();
                    }
                });
                $(".cVideo").click(function () {
                    if ($(this).attr('data') == 'cover-program') {
                        $("#cover-program-cfm").css('display', "inline");
                    } else {
                        $("#cover-program-cfm").hide();
                    }
                });
                $('#ase-close').on('click', function () {
                    VODNew.AccurateFrame.accurateStartEndRemove()
                });
            },

            // 显示和隐藏打点打条列表
            ShowAndHideSegmentationList: function (mode) {
                var list = $(".segmentation").find("div[dname=segmentation_div]");
                var aTag = $("a[action-name=segmentation]");

                if (mode == "close") {
                    list.hide();
                    list.attr("data-show", "false");
                    if (!aTag.hasClass("segmentation_grey")) {
                        aTag.addClass("segmentation_grey");
                    }
                } else {
                    this.ShowAndHideSegmentationAssistList("close");
                    if (list.attr("data-show") == "false") {
                        list.show();
                        list.attr("data-show", "true");
                        aTag.removeClass("segmentation_grey")
                    } else {
                        list.hide();
                        list.attr("data-show", "false");
                        if (!aTag.hasClass("segmentation_grey")) {
                            aTag.addClass("segmentation_grey");
                        }
                    }
                }
            },
            ShowAndHideSegmentationAssistList: function (mode) {
                var list = $(".segmentation").find("div[dname=segmentation-assist_div]");
                var aTag = $("a[action-name=segmentation-assist]")
                if (mode == "close") {
                    list.hide();
                    list.attr("data-show", "false");
                    if (!aTag.hasClass("segmentation_grey")) {
                        aTag.addClass("segmentation_grey");
                    }
                } else {
                    this.ShowAndHideSegmentationList("close");
                    if (list.attr("data-show") == "false") {
                        list.show();
                        list.attr("data-show", "true");
                        aTag.removeClass("segmentation_grey")
                    } else {
                        list.hide();
                        list.attr("data-show", "false");
                        if (!aTag.hasClass("segmentation_grey")) {
                            aTag.addClass("segmentation_grey");
                        }
                    }
                }
            },

            // 打开关闭背景颜色
            OpenOrCloseBk: function (self) {
                if (!self.hasClass("switch-position")) {
                    self.addClass("switch-position");
                    VODNew.Dao.storageData('BCS', 'on');
                    $('.fragment-img').removeClass('c000');
                    $('.in-out-mark-s').show();
                } else {
                    self.removeClass("switch-position");
                    VODNew.Dao.storageData('BCS', 'off');
                    $('.fragment-img').addClass('c000');
                    $('.in-out-mark-s').hide();
                }
            },
            doFragmentSubmitRemind: function () {
                var numTime = parseInt($('#picNum').text());
                var totalLength = $("#div_fragment_append").children().length;
                var fragmentElementDiv = $("div[fragment-line='" + totalLength + "']")
                var st = parseInt(fragmentElementDiv.find("input:eq(0)").val());
                if (st >= numTime - 1) {
                    console.log("reach end , need not remind");
                    return
                }
                var et1 = st + 750;
                var et2 = (numTime - 1) - 150;//约5分钟前
                var et = et2 > et1 ? et2 : et1;
                if (et > numTime - 1) {
                    et = numTime - 1
                }
                $("#fragment-dlg").dialog("open");
                $("#fragment-dlg").find("img:eq(0)").attr("src", $("#img-" + st).attr("src"));
                $("#fragment-dlg").find("img:eq(1)").attr("src", $("#img-" + et).attr("src"));
                $("#fragment-dlg").find("span:eq(0)").html(st);
                $("#fragment-dlg").find("span:eq(1)").html(et);
            },
            transToFpTime: function (period) {
                var second = period % 60;
                var minute = ( period % 3600 - period % 60) / 60;
                var hour = (period - period % 3600) / 3600;
                return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + ":" + (second < 10 ? "0" + second : second);
            },

            // 定时提醒
            RegularTimeRemind: function () {
                var regularTime = $("#alert-time").val();

                if (regularTime && regularTime != "undefined") {
                    (function () {
                        var compareTimeRt = -1, //时间比较结果
                        //blinkTimes = 0,     //闪烁次数
                        //settedTime = '',
                            isTimeArriveInt = null;
                        $("#alert-pop").attr("disabled", "disabled");

                        //alert("添加成功");
                        VODNew.Plugin.tips("success", '添加成功');

                        var isTimeArrive = function () {
                            var time = $("#alert-time").val();
                            var now = new Date();
                            var nowStr = VODNew.Util.formatDateTimeFormat(now);
                            compareTimeRt = VODNew.Util.compareTime(time, nowStr);
                        };

                        var titleWink = function () {
                            // blinkTimes++;
                            //if(blinkTimes==3){blinkTimes=1}

                            if (compareTimeRt >= 0) {
                                window.focus();
                                alert('【' + VODNew.Dao.getParamsData().channel_name + '】【' + regularTime + '】预定时间已到!');
                                $("#alert-pop").removeAttr("disabled");
                                $("#alert-time").val("");
                                clearInterval(isTimeArriveInt);
                                return;
                            }
                            setTimeout(titleWink, 200);
                        };

                        isTimeArriveInt = setInterval(isTimeArrive, 200);
                        //settedTime = time;
                        titleWink();

                    })();
                } else {
                    //alert("时间不能为空");
                    VODNew.Plugin.tips("error", '时间不能为空');
                }
            },

            globalEvent: function (e) {
                console.log("e.keyCode", e.keyCode);
                var self = this;
                var settings = VODNew.Dao.settings;
                var global = VODNew.Config.Global;

                // textarea去除快捷键
                if ($('textarea').is(":focus")) {
                    return true;
                }
                if ($('input').is(":focus")) {
                    return true;
                }

                if (e.which == VODNew.Config.KEY_CODE.ESC) { // 打点精确化,调出该图片所有上所对应的所有帧  对应快捷键为 ESC
                    VODNew.AccurateFrame.accurateStartEndRemove();
                    return false;
                }

                if (this.checkDlgOpen(e)) {
                    return true;
                }
                // 文本框去除快捷键
                if ($("#cForm,#dForm").find('input[type=text]').is(":focus")) {
                    return true;
                }
                if (e.which == VODNew.Config.KEY_CODE.SPACE) { //播放器 播放/暂停
                    e.preventDefault();
                    VODCom.Player.changePlayPause( "flash" );
                    return true;
                }
                if (e.which == VODNew.Config.KEY_CODE.G &&  VODNew.Config.GREY_MODE.inRange ) { //查看标题自动识别
                    //$("button[name=btn_submit_fragment]:visible")
                    $("button[name=btn_get_auto_title]").click();
                    return true;
                }

                if (e.which == VODNew.Config.KEY_CODE.Y) { //提交分片
                    //$("button[name=btn_submit_fragment]:visible")
                    VODNew.Util.doShortcutFragmentSubmit();
                    return true;
                }

                if (e.which == VODNew.Config.KEY_CODE.B) { //清除收纳
                    VODCom.Pic.clear();
                    return true;
                }

                if (e.which == VODNew.Config.KEY_CODE.ZERO && e.ctrlKey) {
                    $('[role="alert"]').hide();
                    return true;
                }

                if (e.which == VODNew.Config.KEY_CODE.Z) { //提交删除
                    VODNew.Advert.del_submit();
                    return true;
                }

                if (e.which == VODNew.Config.KEY_CODE.A) { //提交打点
                    VODNew.Util.dot_submit()
                    $('#addInfo').removeAttr('disabled').html('提交');
                    return true;
                }
                var redParent = $('.red').parent();
                var red = $('.red').parent().find("div");

                if (e.which == VODNew.Config.KEY_CODE.V) { //删除开始
                    if (settings.stime >= 0) {
                        if (redParent.find('.ad-l') > 0 || redParent.find('.p-r').length > 0 || redParent.find('.p-l').length > 0) {
                            return false;
                        }
                        $('.ad-l').remove();
                        if (!$('.old').hasClass('ad-l') && !$('.old').hasClass('ad-r')) {
                            $('.old').remove();
                        }
                        $('.red').addClass('ad-l');
                        $('.ad-l').removeClass('ad-r');
                        $('.ad-l').html("广<br />告<br />头");
                        $('input[name=d_sTime]').val(settings.stime);
                    }
                    return true;
                }
                if (e.which == VODNew.Config.KEY_CODE.C) { //删除结束
                    if (settings.etime >= 0) {

                        if (redParent.find('.ad-r').length > 0 || redParent.find('.p-r').length > 0 || redParent.find('.p-l').length > 0) {
                            return false;
                        }
                        var tmp_stime = $('input[name=d_sTime]').val();
                        if (tmp_stime.length && parseInt(tmp_stime) > parseInt(settings.etime)) {
                            //alert('起始帧不能大于结束帧!');
                            VODNew.Plugin.tips("error", "起始帧不能大于结束帧");
                            return false;
                        }
                        $('.ad-r').remove();
                        if (!$('.old').hasClass('ad-r') && !$('.old').hasClass('ad-l')) {
                            $('.old').remove();
                        }
                        $('.red').addClass('ad-r');
                        $('.ad-r').removeClass('ad-l');
                        $('.ad-r').html("广<br />告<br />尾");
                        $('input[name=d_eTime]').val(settings.etime);
                    }
                    return true;
                }
                if (red.length > 0) {
                    if (e.which == VODNew.Config.KEY_CODE.T) { //分片终点
                        VODNew.Util.doShortcutSetFragmentEnd();
                        return true;
                    }
                    if (e.which == VODNew.Config.KEY_CODE.M) { //打收纳头
                        VODCom.Pic.recordStart();
                        return true;
                    }
                    if (e.which == VODNew.Config.KEY_CODE.N) { //打收纳尾
                        VODCom.Pic.recordEnd();
                        return true;
                    }

                    var skip = redParent.find('.ad-r').length > 0 || redParent.find('.ad-l').length > 0
                    if (e.which == VODNew.Config.KEY_CODE.F) { //打开始
                        if (VODNew.Util.isAppendFragmentMode()) {
                            return false;
                        }
                        if (skip) {
                            return true;
                        }
                        VODCom.NewsHighlight.setNewStart()
                        return;
                    }
                    if (e.which == VODNew.Config.KEY_CODE.D) { //打结束
                        if (skip) {
                            return true;
                        }
                        VODCom.NewsHighlight.setNewEnd();
                        VODNew.Util.fillDefaultTitle();
                        return;
                    }
                    if (e.which == VODNew.Config.KEY_CODE.S) { //打封面
                        if (skip) {
                            return true;
                        }
                        VODCom.NewsHighlight.setNewImage()
                        return;
                    }
                    if (e.which == VODNew.Config.KEY_CODE.R) { //标题ocr识别
                        VODNew.MarkOcrManager.doMarkOcrImage();
                        return;
                    }
                    if (e.which == VODNew.Config.KEY_CODE.LEFT_SQUARE_BRACKET) {
                        VODCom.NewsHighlight.setMaskStart();
                        return;
                    }
                    if (e.which == VODNew.Config.KEY_CODE.RIGHT_SQUARE_BRACKET) {
                        VODCom.NewsHighlight.setMaskEnd();
                        return;
                    }
                    if (e.which == VODNew.Config.KEY_CODE.BACKSLASH) {
                        VODNew.MaskManager.modifyMaskEntity();
                        return;
                    }
                }

                if (e.which == VODNew.Config.KEY_CODE.Q) { // 打点精确化,调出该图片所有上所对应的所有帧  对应快捷键为 q
                    if (!e.altKey) {
                        VODNew.AccurateFrame.handler_keyCodeQ();
                    } else {
                        VODNew.MaskManager.addMaskEntity()
                    }
                    return true;
                }
                if (e.keyCode == VODNew.Config.KEY_CODE.W) // 鼠标悬浮快捷键w
                {
                    var playOneInfo = VODNew.Dao.playOneInfo;
                    if (playOneInfo.mouseenter == true) {
                        VODCom.Player.updatePosition({left: playOneInfo.left, top: playOneInfo.top})
                        VODCom.Player.viewOne(playOneInfo.time);
                    }
                    return true;
                }

                if (e.keyCode == VODNew.Config.KEY_CODE.X) // ocr快捷键 x
                {
                    VODNew.Evt.ShowAndHideSegmentationList();
                    return true;
                }
                if (e.keyCode == VODNew.Config.KEY_CODE.E) // ocr快捷键 E
                {
                    VODNew.Evt.ShowAndHideSegmentationAssistList();
                    return true;
                }
                if (e.keyCode == VODNew.Config.KEY_CODE.LEFT) { //左
                    VODNew.Util.dealDirectionKey(VODNew.Config.KEY_CODE.LEFT, settings);
                    return false;
                }
                if (e.keyCode == VODNew.Config.KEY_CODE.RIGHT) { //右
                    VODNew.Util.dealDirectionKey(VODNew.Config.KEY_CODE.RIGHT, settings);
                    return false;
                }
                if (e.keyCode == VODNew.Config.KEY_CODE.UP) { //上
                    VODNew.Util.dealDirectionKey(VODNew.Config.KEY_CODE.UP, settings);
                    return false;
                }
                if (e.keyCode == VODNew.Config.KEY_CODE.DOWN) { //下
                    VODNew.Util.dealDirectionKey(VODNew.Config.KEY_CODE.DOWN, settings);
                    return false;
                }
                return true;
            },
            checkDlgOpen:function(){
                if (VODNew.AccurateFrame.isDlgOpen()) {
                    console.log(" VODNew.AccurateFrame is open");
                    return true;
                }
                var temp = [];
                temp.push("#auto_title-dlg");
                temp.push("#image_mark-dlg");
                temp.push("#fragment-dlg");
                temp.push("#image_mask-dlg");
                temp.push("#epg_alert_dlg");
                temp.push("#epg_confirm_dlg");
                var needBreak = false;
                $.each( temp,function(i,elemt){
                    if ($(elemt).is(":visible")) {
                        console.log(elemt + "  is open");
                        needBreak = true;
                        return false
                    }
                } );
                if(needBreak){
                    return true;
                }
                return false
            }
        };

    }
);
define(
    '../vodnew/VODNew.Dao',['require','exports','module'],function (require, exports, module) {
        VODNew.Dao = $.extend({}, EpgWeb.Dao, {
            cache: {},
            settings: {
                index: 1,
                newsSubmitIndex: 1,
                newsDelIndex: 1,

                stime: 0,
                etime: 0,
                pic: 0,
                taskid: 0,
                lastImg: 0,
                delList: [],
                subData: [],
                //       needDatas: [],
                isStart: false,
                isSetFpTime: false,
                lb: 1,
                firstFpTime: 0,
                last_i: 0,   // 上次识的库索引
                adLibList: [],
                isOver: 1,  //防止并发
                fpTime: 'fp_time',

                // page use
                startQuery: "",
                period: '',
                linePicNum: 9,
                today: '',
                //   videonameArr:[],
                g_ocrList: [],
                g_acrList: [],
                reg_last_id: 0
            },
            playOneInfo: {mouseenter: false},
            getParamsData: function () {
                return this.getDataByName("params");
            },
            getDotData: function () {
                return this.getDataByName("dot");
            },
            getDataByName: function (targetName) {
                if (!this.cache.hasOwnProperty(targetName)) {
                    if (this.hasOwnProperty("method_" + targetName)) {
                        var target = this["method_" + targetName]();
                        this.cache[targetName] = target;
                        return target;
                    } else {
                        return null;
                    }
                } else {
                    return this.cache[targetName];
                }
            },
            method_params: function () {
                var queryStringObj = VODNew.Util.getUrlParams();
                var obj = {};
                obj["channel_name"] = queryStringObj['channel_code'];
                obj["ip"] = queryStringObj['ip'];
                obj["freeType"] = queryStringObj['free_type'];
                obj["_channel_id"] = queryStringObj['channel_id'];
                obj["_channel_name_str"] = queryStringObj['cn'];
                obj["locationCategory"] = queryStringObj['locationCategory'];
                obj["location"] = queryStringObj['location'];
                obj["startTime"] = queryStringObj['startTime'];
                obj["endTime"] = queryStringObj['endTime'];
                VODNew.Config.MASK_TEST = queryStringObj['MASK_TEST'] || null;
                return obj;
            },
            method_dot: function () {
                var params = this.getParamsData();
                var obj = {};
                obj.dotUrl = 'http://' + params.ip + ':8080/dot/dodot';
                obj.adUrl = 'http://' + params.ip + ':8080/dot/doadstore'; // 广告入库学习
                obj.listUrl = 'http://' + params.ip + ':8080/dot/json';
                obj.initUrl = 'http://' + params.ip + ':8080/dot/init';
                // obj.cateUrl = 'http://' + params.ip + ':8080/dot/cate';
                obj.sty2Url = 'http://' + params.ip + ':8080/dot/sty2';//智能分析
                obj.ocrUrl = 'http://' + params.ip + ':8080/dot/ocr';
                obj.acrUrl = 'http://' + params.ip + ':8080/dot/acr';
                obj.channelInfoUrl = 'http://' + params.ip + ':8080/channel/channelinfo';
                obj.analysis = 'http://' + params.ip + ':9090/dot/analysis';
                obj.sty = 'http://' + params.ip + ':8080/dot/sty'; // 自动拆条
                obj.codeVersionUrl = 'http://' + params.ip + ':8080/version'; // 编码器版本号
                obj.smartLibrary = 'http://' + params.ip + ':8080/dot/';

                // http://10.23.70.35:8080/dot/ocrimage?key=33839&image_id=18&channel_id=233&from_client=true
                obj.ocrimage = 'http://' + params.ip + ':8080/dot/ocrimage'; // 获取生成原始码流图片接口
                //http://10.6.5.125:8080/dot/findocrimage?key=xx&from_client=true
                obj.findImage = 'http://' + params.ip + ':8080/dot/findocrimage';// 获取图片接口
                //http://10.23.70.35:8080/dot/ocrposition?key=33839&image_id=18&channel_id=233&x=1&y=2&w=255&h=400&from_client=true
                obj.ocrposition = 'http://' + params.ip + ':8080/dot/ocrposition';// 前端截图后将坐标传给服务器接口
                obj.ocrresult1 = 'http://' + params.ip + ':8080/dot/ocrresult1';// 前端截图后将坐标传给服务器接口
                obj.ocrresult2 = 'http://' + params.ip + ':8080/dot/ocrresult2';// 前端截图后将坐标传给服务器接口
                //    obj.ocrresult1 = 'http://' + params.ip + ':8080/dot/ocrresult122';// 前端截图后将坐标传给服务器接口
                obj.appendUrl = 'http://' + params.ip + ':8080/dot/append';// 分片追加接口

                // /dot/delogoimage?image_id=XX&channel_code=xx&from_client=true&key=xx&delogo=xx
                obj.delogoimage = 'http://' + params.ip + ':8080/dot/delogoimage'// 遮标预览
                obj.autoTitleUrl = 'http://' + params.ip + ':8080/dot/autoTitle'// 获取自动识别标题

                obj.doadadd = 'http://' + params.ip + ':8080/dot/doadadd'// 添加广告精确化
                obj.doaddel = 'http://' + params.ip + ':8080/dot/doaddel'// 删除广告精确化

                return obj;
            },
            // 获取合作方信息
            getCooperativePartner: function (options, callback) {
                if (options.channeltype == 'undefined' || options.channelalias == 'undefined' || options.channeltype == '' || options.channelalias == '')
                    return '';
                $.get(VODNew.urlConfig.partnerUrl, options, function (res) {
                    if (res.code == 200) {
                        callback.call(this, res.response.data);
                    } else {
                        console.log("【合作方失败信息】" + res.msg);
                    }
                }, 'json');
            },
            getCodeVersion: function (options) {
                var codeVersionUrl = this.getDotData().codeVersionUrl;
                $.ajax({
                    cache: false,
                    async: false,
                    type: "get",
                    url: codeVersionUrl,
                    data: {
                        'data': JSON.stringify(options)
                    },
                    success: function (data) {
                        VODNew.Dao.storageData('coderVersion', data);
                    },
                    error: function () {
                        console.log('请求编码器版本号失败,请稍后再试！');
                    }
                });
            },
            getChannelType: function (handler) {
                var options = {
                    url: VODNew.Constant.thirdUrl_channel,
                    type: "get",
                    data: {size: 100},
                    success: function (data) {
                        var formatData = [];
                        $.each(data.data, function (i, element) {
                            formatData.push({id: element.id, label: element.name, value: element.name})
                        })
                        handler(formatData);
                        console.log("renderPanel happen");
                    },
                    error: function (data) {
                        console.log("error happen");
                    }
                }
                this.sendProxy(options);
            },
            delNews: function (data, callback) {
                var url = this.getDotData().sty;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                $.ajax(options);
            },
            getNewsList: function (data, callback) {
                var url = this.getDotData().sty;
                //var url = "http://10.23.70.35:8080/dot/sty"
                this.doGet(url, data, callback);
            },
          
            getOcrImage: function (data, callback) {
                var url = this.getDotData().ocrimage;
                this.doGet(url, data, callback);
            },
            doFindImage: function (timeKey, data, callback) {
                var self = this;
                var url = this.getDotData().findImage;
                if (self.cache[timeKey] != null) {
                    clearInterval(this.cache[timeKey].timeId);
                    self.cache[timeKey] = null;
                }
                var tempData = {
                    timeId: 0,
                    restTry: 5
                }
                self.cache[timeKey] = tempData;
                self.cache[timeKey].timeId = setInterval(function () {
                    console.log("开始加载" + timeKey);
                    self.doGet(url, data, function (sdata) {
                        if (sdata.code == "A00000") {
                            console.log("完成加载" + timeKey);
                            clearInterval(self.cache[timeKey].timeId);
                            self.cache[timeKey] = null;
                            callback(sdata);
                        } else {
                            self.cache[timeKey].restTry--;
                            if (self.cache[timeKey].restTry <= 0) {
                                clearInterval(self.cache[timeKey].timeId);
                                self.cache[timeKey] = null;
                                console.log("加载失败"+ timeKey);
                            }
                        }
                    });
                }, 1000)
            },

//            submitOcrposition:function(data,callback){
//                var url = this.getDotData().ocrposition;
//                this.doGet( url,data,callback );
//            },
            getOcrResult: function (data, callback) {
                //  http://10.23.70.35:8080/dot/ocrresult1?image_id=0&channel_code=BJXWGQUDI&from_client=true&key=282&x=0&y=0&w=20&h=20
                var url = this.getDotData().ocrresult1;
                this.doGet(url, data, callback);
            },
            getOcrResult2: function (data, callback) {
                //  http://10.23.70.35:8080/dot/ocrresult1?image_id=0&channel_code=BJXWGQUDI&from_client=true&key=282&x=0&y=0&w=20&h=20
                var url = this.getDotData().ocrresult2;
                this.doGet(url, data, callback);
            },
            getMaskResult: function (data, callback) {
                var url = this.getDotData().delogoimage;
                this.doGet(url, data, callback);
            },


            postOcr2Data: function (data, callback) {
                var options = {
                    type: "post",
                    url: VODNew.urlConfig.submitOcr2DataUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                $.ajax(options, "");
            },
            postAutoTitleData: function (data, callback) {
                var options = {
                    type: "post",
                    url: VODNew.urlConfig.submitAutoTitleDataUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                $.ajax(options, "");
            },
            // original structure
            storageData: function (name, value) {
                var DSN = $('#storage-data');
                if (!value && !name)
                    return '';
                else if (value == undefined)
                    return DSN.data(name);
                else
                    DSN.data(name, value);
            },
            getInitTaskId: function (data, callback) {
                var url = this.getDotData().initUrl;
                this.doGet(url, data, callback);
            },
            submitLogEntity: function (data, callback) {
                var url = VODNew.urlConfig.submitLogUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(data)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/vod/saveLog");
            },
            submitEpisodeLogEntity: function (data, callback) {
                var url = VODNew.urlConfig.submitEpisodeLogUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(data)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/vod/saveEpisodeLog");
            },
            postSync: function (postUrl, postData, handler, sync) {
                var async = sync == null ? true : sync != true;
                var options = {
                    cache: false,
                    async: async,
                    type: "post",
                    dataType: "json",
                    url: postUrl,
                    data: postData,
                    success: function (res) {
                        handler.doSuc(res);
                    },
                    error: function () {
                        handler.doError();
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            dopeditorSubmit: function (sendData, handler) {
                var ajaxTimeoutTest = $.ajax({
                    cache: false,
                    async: false,
                    type: "post",
                    url: VODNew.urlConfig.redirect,
                    timeout: 10000,
                    dataType: "json",
                    data: sendData,
                    success: function (res) {
                        handler.doSuc(res);
                    },
                    error: function (XMLHttpRequest, status) {
                        handler.doError(XMLHttpRequest, status);
                    }
                })
            },
            getAutoTitleList: function (sendData, handler) {
                var url = this.getDotData().autoTitleUrl;
                this.doGet(url, sendData, handler);
                //   handler({code: VODNew.Config.CODE_SUC, title: JSON.stringify(["测试e标题1", "测试标题s12", "测题13","测试标题13","测试标题23","测试标题33","测试标题43","测试标题63"]) });
                //   handler({code: VODNew.Config.CODE_SUC, data: []})
            },
            doAdvertCutAdd: function (sendData, handler) {
                console.log("doAdvertCutAdd:" + JSON.stringify(sendData));
                if (sendData == null) {
                    console.log(JSON.stringify(sendData));
                    handler({code: "A00000"})
                } else {
                    var params = this.getDotData();
                    this.sendAjax(params.doadadd, "post", sendData, handler)

                }
            },
            doAdvertCutDel: function (sendData, handler) {
                console.log("doAdvertCutDel:" + JSON.stringify(sendData));
                if (sendData == null) {
                    console.log(JSON.stringify(sendData));
                    handler({code: "A00000"})
                }
                {
                    var params = this.getDotData();
                    this.doGet(params.doaddel, sendData, handler)
                }

            },
            doAdvertTest: function (handler) {
                var params = this.getDotData();
                this.sendAjax(params.doadadd, "post", {from_client: true}, handler)
            }
        })
    }
);
define(
    '../vodnew/VODNew.EditMerge',['require','exports','module'],function (require, exports, module) {
        VODNew.EditMerge = function (options) {
            this.dao = VODNew.Dao;
            this.task = VODNew.Task;
            this.config = VODNew.Config;
            this.options = options || {};
        };
        Com.inherits(VODNew.EditMerge, Ancestor.Grid, function (options) {
        }).extend({
            init: function () {
                VODNew.Util.nonIntelligentData();
                VODNew.Util.checkGreyMode();
                VODCom.Player.initPlayer({
                    accurateFrame: VODNew.AccurateFrame,
                    dao: VODNew.Dao,
                    tips: VODNew.Plugin.tips
                });
                VODCom.NewsHighlight.bindConfig( VODNew)
                var self = this;
                self.initPointTime();
                $("#navDiv").tabs({active: 1});
                self.initDlg();
                self.bindEvent();
                self.initBodyEvent();
                self.initSuggest();
                self.initInterValTask();
                self.initGrid();
                self.initWordCount();

                self.config.DOT_SUBMIT_TIME = VODNew.Util.formatDateTimeFormat(new Date());
                $("#navMaskDiv").tabs();
                VODNew.Util.checkAdvertSupport();

            },
            initWordCount: function () {
                VODNew.Util.canOverWordCount($("input[name=videoName]"), 43, null, null, function (length) {
                    var infoHint = $("span[span-mode=info]");
                    var warnHint = $("span[span-mode=warn]");
                    if (length >= 0) {
                        infoHint.find("span.leftWordsCount").text(length / 2);
                        infoHint.show();
                        warnHint.hide();
                    } else {
                        infoHint.hide();
                        warnHint.show();
                        warnHint.find("span.overWordsCount").text(-length / 2);
                    }
                });

                VODNew.Util.canOverWordCount($("input[name=image_ocr_title]"), 43, null, null, function (length) {
                    var infoHint = $("span[span-mode=info2]");
                    var warnHint = $("span[span-mode=warn2]");
                    if (length >= 0) {
                        infoHint.find("span.leftWordsCount").text(length / 2);
                        infoHint.show();
                        warnHint.hide();
                    } else {
                        infoHint.hide();
                        warnHint.show();
                        warnHint.find("span.overWordsCount").text(-length / 2);
                    }
                });

                VODNew.Util.canOverWordCount($("input[name=image_auto_title]"), 43, null, null, function (length) {
                    var infoHint = $("span[span-mode=info3]");
                    var warnHint = $("span[span-mode=warn3]");
                    if (length >= 0) {
                        infoHint.find("span.leftWordsCount").text(length / 2);
                        infoHint.show();
                        warnHint.hide();
                    } else {
                        infoHint.hide();
                        warnHint.show();
                        warnHint.find("span.overWordsCount").text(-length / 2);
                    }
                });


                VODNew.Util.limitWordCount($("input[name=fantasyTitle]"), 80, null, null, function (length) {
                    $("span.leftWordsCount1").text(length / 2);
                });
            },

            foldDivMakeUp: function (element) {
                var global = VODNew.Config.Global;
                var style = global.smallPic ? "width:120px;height:96px" : "width:280px;height:220px";
                var htmlArr = [];
                htmlArr.push('<div class="text-center relative" style="' + style + '" fold-key="' + (element.start + "_" + element.end) + '" fold-start="' + element.start + '" fold-end="' + element.end + '">')
                htmlArr.push(' 收纳' + element.start + '~' + element.end);
                htmlArr.push('<br><span style="cursor: pointer" onclick="VODCom.Pic.extendPics(this)">展开</span>');
                htmlArr.push('</div>');
                $(htmlArr.join("")).insertBefore($("#img-" + element.start).parent());
            },

            initBodyEvent: function () {
                var self = this;
                var browser = VODNew.Util.getUserAgent();
                VODNew.Util.detectBrowserSupport(browser);
                VODNew.Util.LayoutInit();

                self.dao.storageData('ASS', 'off'); // 自动拆条开关
                self.dao.storageData('BCS', 'off'); // 背景颜色开关

                VODNew.Evt.InitBindEvt();

                VODNew.Util.browserZoomTips();
                $("body").show();
                $("body").on('click', '[action-name]', function () {
                    var self = $(this),
                        name = self.attr('action-name');
                    switch (name) {
                        case 'segmentation':
                            VODNew.Evt.ShowAndHideSegmentationList();
                            break;
                        case 'segmentation-assist':
                            VODNew.Evt.ShowAndHideSegmentationAssistList();
                            break;
                        case 'switch': // 拆条背景颜色打开与关闭
                            VODNew.Evt.OpenOrCloseBk(self);
                            break;
                        default:
                            break;
                    }
//                    case 'segmentation':
//                    case 'segmentation-assist':
//                    case 'segmentation-fragment':
//                    VODNew.Evt.ShowAndHideList(name);
//                    break;
                });
            },

            initInterValTask: function () {
                var self = this;
                VODNew.Config.HeartBeat = VODNew.Util.createHeartBeatUtil();
                //          setInterval(self.task.getData, 5000);   // 获取图片数据
                // 获取ocr标题数据
                //setInterval(getCate,20000);
                //     setInterval( self.task.doHeartBeat,1000) // 心跳
                VODNew.Config.HeartBeat.pushTask({needBlock: false, gap: {s: 5}, handler: function () {
                    self.task.getData();
                }});
                var fgOptions = {
                    needBlock: true,
                    stop: true,
                    //      gap: {s: 30},
                    gap: auth.dev() ? {m: 2} : {m: 30},
                    handler: function () {
                        console.log("blockHBId  " + VODNew.Config.fgRemindObj.id);
                        if (!VODNew.Util.isAppendFragmentMode()) {
                            VODNew.Config.fgRemindObj.stop = true;
                            return;
                        }
                        VODNew.Evt.doFragmentSubmitRemind();
                    }}
                VODNew.Config.fgRemindObj = VODNew.Config.HeartBeat.pushTask(fgOptions);
                VODNew.Config.Global.sty2Data.list = [];
                VODNew.Config.HeartBeat.start();
            },
            initPointTime: function () {
                //默认时间
                var today_d = new Date();
                if (today_d.getMinutes() > 2) {
                    today_d.setTime(today_d.getTime() - 120000);
                }
                var s_d = VODNew.Util.formatDateTimeFormat(today_d);
                today_d.setTime(today_d.getTime() + 4 * 3600 * 1000);
                var e_d = VODNew.Util.formatDateTimeFormat(today_d);

                $('#inputStartTime').val(s_d);
                $('#inputEndTime').val(e_d);
                if (s_d >= e_d) {
                    return
                }
                VODNew.Util.bindDate("inputStartTime", "inputEndTime", { maxDate: e_d, maxDateTime: new Date(e_d.replace(/-/g, "/")), minDate: s_d, minDateTime: new Date(s_d.replace(/-/g, "/")), slider: true});
                $("input[name=inputStartTime]").datetimepicker("setDate", new Date(s_d.replace(/-/g, "/")));
                $("input[name=inputEndTime]").datetimepicker("setDate", new Date(e_d.replace(/-/g, "/")));
            },
            initDlg: function () {
                var self = this;
                self.initAlterTitleDlg();
                self.initAlertDlg();
                self.initImageMarkDlg();
                self.initFragmentDlg();
                self.initImageMaskDlg();
                self.initHelp();
                VODCom.AutoTitle.initAutoTitleDlg({
                    settings: self.dao.settings,
                    dao: self.dao,
                    tips: VODNew.Plugin.tips,
                    validate: VODNew.Plugin.Validate,
                    config: self.config,
                    util: VODNew.Util,
                    body:$("body")
                });
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                $('#alert-time').datetimepicker();
                $('button[data-dismiss=modal]').on('click', function () {
                    VODNew.AccurateFrame.accurateStartEndRemove()
                });
            },
            initHelp: function () {
                var self = this;
                $("#help-dlg").dialog({
                    title: "打点系统帮助",
                    resizable: false,
                    dialogClass: 'alert',
                    autoOpen: false,
                    width: 660,
                    modal: true
                })
                var innerText = "";
                $.each(VODNew.Config.HELP_DATA, function (i, data) {
                    innerText += '<tr><td>' + data[0] + '</td><td>' + data[1] + '</td></tr>'
                })
                $("#help-dlg").find("tbody").html(innerText);


                $("#help-pop").bind("click", function () {
                    var helpDlg = $("#help-dlg")
                    if (self.dao.storageData('coderVersion') == undefined) {
                        self.dao.getCodeVersion({});
                        if (self.dao.storageData('coderVersion') == undefined) {
                            self.dao.storageData('coderVersion', '0 | 0 | 0');
                        }
                        helpDlg.dialog("open");
                        helpDlg.find("label[name=coderVersion]").html("版本 V3.2.2 | " + self.dao.storageData('coderVersion'));
                    } else {
                        helpDlg.dialog("open");
                    }
                })
            },
            initAlterTitleDlg: function () {
                $("#alter_title-dlg").dialog({
                    title: "请选择该新闻标题",
                    resizable: false,
                    dialogClass: 'alert',
                    autoOpen: false,
                    width: 350,
                    modal: true
                })

                $("button[name=alter_title-ok]").bind("click", function (e) {
                    VODNew.Util.updateNewsGridRowData();
                    $("#alter_title-dlg").dialog("close");
                });
                $("button[name=alter_title-cancel]").bind("click", function (e) {
                    $("#alter_title-dlg").dialog("close");
                });
            },


            initAlertDlg: function () {
                $("#alert-dlg").dialog({
                    title: "定时提醒",
                    resizable: false,
                    dialogClass: 'alert',
                    autoOpen: false,
                    width: 600,
                    modal: true
                })
                $("#alert-pop").bind("click", function () {
                    $("#alert-dlg").dialog("open");
                })

                $("button[name=alert-dlg-cancel]").bind("click", function (e) {
                    $("#alert-dlg").dialog("close");
                });
                $("button[name=alert-dlg-ok]").bind("click", function (e) {
                    VODNew.Evt.RegularTimeRemind();
                    $("#alert-dlg").dialog("close");
                });
            },
            initImageMarkDlg: function () {
                $("#image_mark-dlg").dialog({
                    title: "图片标题识别",
                    resizable: false,
                    dialogClass: 'alert',
                    autoOpen: false,
                    width: 1120,
                    modal: true
                })

                $("button[name=image_mark-ok]").bind("click", function (e) {
                    VODNew.MarkOcrManager.fillByOcrTitle();
                    $("#image_mark-dlg").dialog("close");
                });
                $("button[name=image_mark-cancel]").bind("click", function (e) {
                    $("#image_mark-dlg").dialog("close");
                });
                VODNew.Config.CropInstance = $.Jcrop("#ocr_image", {
                    onChange: VODNew.MarkOcrManager.doCropChange,
                    onSelect: VODNew.MarkOcrManager.doCropSelect,
                    boxHeight: 603,
                    minSelect: [10, 10]
                })
            },
            initImageMaskDlg: function () {
                $("#image_mask-dlg").dialog({
                    title: "遮标",
                    resizable: false,
                    dialogClass: 'alert',
                    autoOpen: false,
                    width: 1120,
                    modal: true
                })
                VODNew.MaskManager.initManager({
                    gridTarget: $("#mask_list"),
                    dlgTarget: $("#image_mask-dlg"),
                    maskDivTarget: $("#maskDiv"),
                    imageTarget: $("#mask_image"),
                    btn_preview: $("button[name=image_mask-preview]"),
                    btn_ok: $("button[name=image_mask-ok]"),
                    btn_cancel: $("button[name=image_mask-cancel]")
                })
            },
            initFragmentDlg: function () {
                $("#fragment-dlg").dialog({
                    title: "快速直转点提交提示",
                    resizable: false,
                    dialogClass: 'no-close',
                    autoOpen: false,
                    width: 600,
                    modal: true,
                    closeOnEscape: false
                })

                $("button[name=fragment-ok]").on("click", function (event) {
                    $("#fragment-dlg").dialog("close");
                    VODNew.Util.autoFillFragmentEnd();
                    VODNew.Util.handlerRemoveFgRemindBlock();
                })
                $("button[name=fragment-cancel]").on("click", function (event) {
                    $("#fragment-dlg").dialog("close");
                    VODNew.Util.handlerRemoveFgRemindBlock();
                })
            },

            queryBeforeInit: function () {
                VODNew.Config.PageBeanFrame.setNewData([]);
                VODNew.Config.PageBeanAdvert.setNewData([]);
                VODNew.Config.PageBeanNewsSubmit.setNewData([]);
                VODNew.Config.PageBeanNewsDel.setNewData([]);
                VODNew.Config.lastSubmitObj = { programId: -1, hasSubmit: false}
                VODNew.Config.lastLegoSubmitObj = { programId: -1, hasSubmit: false}
                VODNew.Config.fragmentPid = 0;
                VODNew.Config.LAST_FRAGMENT_REMIND_TIME = 0;
                VODNew.Config.LAST_FRAGMENT_REMIND_ENABLE = false;
                VODNew.Config.AUTO_SUBMIT_TRIGGER = false;

                VODNew.Util.updateGridFrame();
                VODNew.Util.updateGridAdvert();
                VODNew.Util.updateGridNewsSubmit();
                VODNew.Util.updateGridNewsDel();
                VODNew.MaskManager.clearMaskEntity();
                VODNew.AccurateFrame.doReset();
                VODNew.AccurateFrame.adTipRemove();
                VODCom.NewsHighlight.setHighLight(null);
            },

            queryImage: function () {
                var self = this;
                var settings = self.dao.settings;
//                var sty = '';
                if (self.dao.storageData('ASS') == 'on') {
                    if (!self.dao.storageData('sty-intval')) {
                        //   sty = setInterval(self.dao.getSty, 10000);
                        self.dao.storageData('sty-intval', 1);
                    }
                } else {
                    //  clearInterval(sty);
                    self.dao.storageData('sty-intval', 0);
                    self.dao.storageData('sty-index', 0);
                    VODNew.g_mi = 0;
                    VODNew.g_i = 0;
                }

                // 清除已列拆条
                $('.inner-table').parents('tr').remove();
                $('.merg-seg-tips,.auto-seg-tips').show();

                self.updateDaoSetting();

                var start = VODNew.Util.validStart();
                if (!start) {
                    return false;
                }
                $('#makedImg').html('正在请求数据，请等待！');
                $('#makedImg').data("fold", []);
                var paramsData = self.dao.getParamsData();
                var dotData = self.dao.getDotData();
                VODNew.Util.clearOldTaskData();
                self.dao.getInitTaskId({
                    'start': start,
                    'period': settings.period,
                    'code': paramsData.channel_name,
                    'from_client': true
                }, function (data) {
                    if (data == null) {
                        VODNew.Plugin.tips("error", '网络错误');
                    } else {
                        if (data.taskid != null && data.taskid > 0) {
                            settings.taskid = parseInt("" + data.taskid);
                            settings.lastImg = 0;
                            //开始请求数据
                            settings.isStart = true;
                            $('#makedImg').empty();
                            self.task.getData();
                            self.queryNews();
                        } else {
                            //alert('系统错误:任务id为空');
                            VODNew.Plugin.tips("error", '系统错误:任务id为空');
                        }
                    }
                })
                //////////////////////////////////////////
                //////////////////////////////////////////
            },
            bindChangePicEvent: function () {
                var self = this;
                var settings = self.dao.settings;
                var global = VODNew.Config.Global;

                VODCom.Pic.eventManager.bindEvent("fold_makeUp", function (element) {
                    self.foldDivMakeUp(element)
                })

                $('#changeBigPic').bind("click", function (event) {
                    settings.lb = 1;
                    $('.right img').css({
                        'width': '264px',
                        'height': '204px'
                    });
                    VODNew.Config.Global.picWH = VODNew.Config.BIG_PIC_MODE;
                    $(this).addClass('btn-primary');
                    $('#changeSmallPic').removeClass('btn-primary');
                    $('.breakWord').remove();
                    if (global.isClicked) {
                        if ($('.red').length > 0) {
                            var sTop = $('#makedImg').scrollTop() + $('.red').offset().top;
                            $('#makedImg').scrollTop(sTop);
                        }
                    }
                    global.smallPic = false;
                    $('.fp_time').removeClass('fp_time').addClass('fp_time2');
                    $('.in-out-mark-s').addClass('in-out-mark-b');
                    settings.fpTime = 'fp_time2';
                    VODNew.Util.getLineWidth();
                    $("#play-one").css({
                        width: "274px",
                        height: "210px"
                    });
                    VODCom.Pic.eventManager.dispatchEvent({type: "change_big_pic", data: []});
                })
                $('#changeSmallPic').bind("click", function (event) {
                    settings.lb = 1;
                    $('.right img').css({
                        'width': '104px',
                        'height': '64px'
                    });
                    VODNew.Config.Global.picWH = VODNew.Config.SMALL_PIC_MODE;
                    $(this).addClass('btn-primary');
                    $('#changeBigPic').removeClass('btn-primary');
                    $('.breakWord').remove();
                    if (global.isClicked) {
                        if ($('.red').length > 0) {
                            var sTop = $('#makedImg').scrollTop() + $('.red').offset().top;
                            $('#makedImg').scrollTop(sTop);
                        }
                    }
                    global.smallPic = true;
                    $('.fp_time2').removeClass('fp_time2').addClass('fp_time');
                    $('.in-out-mark-s').removeClass('in-out-mark-b');
                    settings.fpTime = 'fp_time';
                    VODNew.Util.getLineWidth();
                    $("#play-one").css({
                        width: "140px",
                        height: "105px"
                    });
                    VODCom.Pic.eventManager.dispatchEvent({type: "change_small_pic", data: []});
                })
            },

            bindEvent: function () {
                var self = this;
                VODNew.Evt.InitBindEvt();
                $('#submitStartTime').click(function () {
                    self.queryBeforeInit();
                    self.queryImage();
                })


                self.bindChangePicEvent();
                $("button[name=cancel-import]").bind("click", function (event) {
                    VODNew.Util.doClearImportData();
                })

                self.bindReviewInfo();
                self.bindAddInfo();
                self.bindJumpSubmitHandler();
                self.bindMarkImgHandler()

                $('select[name=jumpType]').change(function () {
                    if ($(this).val() == 1) {
                        $('#jumpContent').val('00:00:00');
                    } else {
                        $('#jumpContent').val('0');
                    }
                })
                $('#autoRunPic').click(function () {
                    if ($(this).prop('checked')) {

                        $('#makedImg').scrollTop($('#makedImg')[0].scrollHeight);
                    }
                })

                $("input[name=videotype]").bind('click', function () {
                    $('input[name=albumName],input[name=categoryName]').removeAttr('disabled');
                    //settings.videonameArr = [];
                    $('input[name=videoName]').suggest("setValue", "");
                    $("input[name=albumName]").suggest("setValue", "");
                    if ($(this).val() == -1) {
                        $('#fantasyTitleDiv').css('display', 'block');
                        if ($("input[name=categoryName]").suggest("getValue") == "25" && $("input[name=categoryName]").val() == "资讯") {
                            $("#locationDiv").show();
                        } else {
                            $("#locationDiv").hide();
                        }
                    } else {
                        $("#locationDiv").hide();
                        $('#fantasyTitleDiv').css('display', 'none');
                    }
                    if ($(this).val() == 0 || $(this).val() == 1) {
                        $('input[name=albumName],input[name=categoryName]').attr("disabled", true);
                    }
                    var categoryName = $("input[name=categoryName]").val();
                    VODNew.Util.setCooperativePartner(categoryName);
                });

                $("input[name=isAppendFragment]").bind("click", function () {
                    if ($(this).val() == 1) {
                        if (VODNew.Util.checkChangeFragmentMode()) {
                            VODNew.Util.transToFragmentMode();
                        } else {
                            return false;
                        }
                    } else if ($(this).val() == 0) {
                        VODNew.Util.transToNormalMode();
                    }
                })

                $('input[name=eTime]').blur(function () {
                    VODNew.Util.fillDefaultTitle();
                })
                $("#div_fragment_append").delegate("button[name=btn_submit_fragment]", "click", function (event) {
                    var _self = this;
                    var parentDiv = $(_self).parent()
                    var eTimeVal = parentDiv.find("input:eq(1)").val();
                    var sTimeVal = parentDiv.find("input:eq(0)").val();
                    if (eTimeVal.length == 0 || isNaN(eTimeVal)) {
                        return;
                    }
                    if (parseInt(sTimeVal) >= parseInt(eTimeVal)) {
                        VODNew.Plugin.tips("error", "分片起始帧需小于分片结束帧");
                        return;
                    }
                    var finalETime = $("input[name=eTime]").val();
                    if (finalETime.length > 0 && !isNaN(finalETime) && parseInt(eTimeVal) > parseInt(finalETime)) {
                        VODNew.Plugin.tips("error", "分片结束帧大于成片结束帧");
                        return;
                    }
                    var handler = function () {
                        $(_self).hide();
                        VODNew.Util.handlerRemoveFgRemindBlock();
                        VODNew.Util.doFragmentSubmit(parentDiv, {
                            doSuc: function () {
                                VODNew.Util.addToDivFragment();
                            },
                            doError: function (msg, logOnly) {
                                console.error(msg);
                                if (logOnly == null || !logOnly) {
                                    VODNew.Plugin.tips("error", msg);
                                }
                                $(_self).show();
                            },
                            doRevert: function () {
                                $('input[name=isAppendFragment]').removeAttr("disabled");
                                $('input[name=isAppendFragment][value="0"]').click();
                            }
                        })
                    }

                    if (VODNew.Config.AUTO_SUBMIT_TRIGGER == true) {
                        VODNew.Config.AUTO_SUBMIT_TRIGGER = false;
                        handler();
                    } else {
                        SystemDialog.queryConfirm(VODNew.Config.REMIND_MSG_INFO.FRAGMENT_SUBMIT, function (flag) {
                            if (flag == true) {
                                handler();
                            }
                        }, {"btn_ok": "确认提交分片", "btn_cancel": "去提交广告" })
                    }
                })

                $("#div_fragment_append").delegate("button[name=btn_preview_fragment]", "click", function (event) {
                    var parentDiv = $(this).parent()
                    var eTimeVal = parentDiv.find("input:eq(1)").val();
                    if (eTimeVal.length == 0 || isNaN(eTimeVal)) {
                        return;
                    }
                    var sTimeVal = parentDiv.find("input:eq(0)").val();
                    if (parseInt(sTimeVal) > parseInt(eTimeVal)) {
                        VODNew.Plugin.tips("error", "分片起始帧不能大于分片结束帧");
                        return;
                    }
                    console.log(" btn_preview_fragment click ");
                    VODNew.Util.doReview(parentDiv.find("input:eq(0)").val(), eTimeVal, true);
                })

                $("#div_fragment_append").delegate("div>input", "keyup afterpaste", function (event) {
                    this.value = this.value.replace(/\D/g, '')
                })
                VODCom.AutoTitle.bindEvent();
            },
            updateDaoSetting: function () {
                var self = this;
                var settings = {
                    index: 1,
                    newsSubmitIndex: 1,
                    newsDelIndex: 1,
                    stime: 0,
                    etime: 0,
                    pic: 0,
                    taskid: 0,
                    lastImg: 0,
                    delList: [],
                    subData: [],
                    needDatas: [],
                    isStart: false,
                    isSetFpTime: false,
                    lb: 1,
                    firstFpTime: 0,
                    last_i: 0,   // 上次识的库索引
                    adLibList: [],
                    isOver: 1  //防止并发
                }
                if (!$('#changeBigPic').hasClass('btn-primary')) {
                    settings.fpTime = 'fp_time';
                } else {
                    settings.fpTime = 'fp_time2';
                }
                VODNew.Util.updateObjectData(settings, self.dao.settings);
            },
            bindAddInfo: function () {
                $("#d_addInfo").on("click", function () {
                    VODNew.Advert.del_submit()
                })
                $('#addInfo').click(function () {
                    VODNew.Util.dot_submit()
                    $('#addInfo').removeAttr('disabled').html('提交');
                });
            },
            bindReviewInfo: function () {
                var self = this;
                $('#reviewInfo').bind("click", function (e) {
                    var sTime = $('input[name=sTime]').val(),
                        eTime = $('input[name=eTime]').val();
                    VODNew.Util.doReview(sTime, eTime, true)
                })
                $('#d_reviewInfo').bind("click", function (e) {
                    var sTime = $('input[name=d_sTime]').val(),
                        eTime = $('input[name=d_eTime]').val();
                    VODNew.Util.doReview(sTime, eTime, false)
                })

            },

            bindMarkImgHandler: function () {
                var self = this;
                var settings = self.dao.settings;
                $('#makedImg').on('click', 'img.fragment-img', function () {
                    VODNew.Config.Global.isClicked = true;  // 大小图片切换滚动到当前图片用
                    if ($(this).parent().find(".layout").hasClass("red")){
                        if (VODCom.H5Player.getPlayerData("flash").video.paused) {
                            VODCom.Player.doViewImage(true);
                        }
                        return;
                    }
                    $('.layout').removeClass('red');
                    if ($(this).parent().find(".layout").length !== 0)
                        $(this).parent().find(".layout").addClass("red");
                    else
                        $(this).parent().append(VODNew.Config.RED_LAYOUT);
                    settings.pic = settings.etime = settings.stime = $(this).parent().find('.pid').text().replace(/\s+/g, "");
                    VODCom.Player.viewStopImage(settings.pic)
                })
            },
            bindJumpSubmitHandler: function () {
                $('#jumpSubmit').click(function () {
                    var jumpType = $('select[name=jumpType]').val();
                    var jc = $('#jumpContent').val();
                    if (!VODNew.Util.isJumpData(jc, jumpType)) {
                        VODNew.Plugin.tips("error", '跳转输入格式错误');
                        return false;
                    }
                    var jumpContent = null;
                    if (jumpType == 1) {
                        jumpContent = jc.replace(/:/g, "-");
                        if (!$('.relative').hasClass(jumpContent)) {
                            var temStr = jumpContent.substr(jumpContent.length - 2);
                            if (temStr.length == 2 && temStr.substr(0, 1) == '0') {
                                temStr = temStr.charAt(temStr.length - 1);
                            }
                            var lasStr = parseInt(temStr);
                            if (lasStr == 0) {
                                lasStr += 10;
                            }
                            var beforeStr = jumpContent.substr(0, jumpContent.length - 2)
                            var untilStr = lasStr - 10;
                            if (untilStr < 0)
                                untilStr = 0;
                            var us
                            for (var i = lasStr; i >= untilStr; i--) {
                                if (i < 10) {
                                    us = 0 + String(i);
                                } else {
                                    us = String(i);
                                }
                                us = beforeStr + us;

                                if ($('.relative').hasClass(us)) {
                                    jumpContent = us;
                                    break;
                                }
                            }
                        }
                    } else {
                        jumpContent = jc + '-jump';
                    }
                    if ($('.relative').hasClass(jumpContent)) {
                        $('#makedImg').scrollTop(0)
                        sTop = $('.' + jumpContent).offset().top - 100;
                        $('#makedImg').scrollTop(sTop);
                    } else {
                        //alert('没有这帧');
                        VODNew.Plugin.tips("error", '没有这帧');
                    }
                })
            },
            initSuggest: function () {
                var self = this;


                var channelTypeSuggest = {
                    options: {
                        source: VODNew.urlConfig.redirect,
                        renderPanel: function (handler) {
                            self.dao.getChannelType(handler)
                        },
                        select: function (event, object) {
                            console.log("trihger  channelTypeSuggest");
                            $("input[name=albumName]").removeAttr("disabled");
                            $("input[name=albumName]").suggest("setValue", "");
                            if (object.item.id == 25 && $('input[name=videotype]:checked').val() == -1) {
                                $("#locationDiv").css('display', 'inline-block');
                            } else {
                                $("#locationDiv").css('display', 'none');
                            }
                            VODNew.Util.setCooperativePartner(object.item.value);
                            $("input[name=categoryName]").attr("bind-sel-name", object.item.value);
                            $("input[name=categoryName]").attr("bind-sel-id", object.item.id);
                            return true;
                        },
                        autoFilter: false,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var params = term.length == 0 ? {size: 100} : {word: term, size: 100}
                            var requestData = {url: VODNew.Constant.thirdUrl_channel, type: "get", params: params, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"];
                                itemData["value"] = item["name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            return item["label"];
                        }
                    }
                }
                var albumSuggest = {
                    options: {
                        source: VODNew.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            return [];
                        },
                        getParam: function (term) {
                            var channelId = $("input[name=categoryName]").suggest("getValue")
                            var requestData = {url: VODNew.Constant.thirdUrl_album, type: "get", params: {word: term, type: "displayName", filter_EQL_channel: channelId}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["entityId"];
                                itemData[options.labelKey] = item["displayName"];
                                itemData["value"] = item["displayName"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item["label"];
                        }
                    }
                }
                var locationSuggest = {
                    options: {
                        source: VODNew.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            return [];
                        },
                        getParam: function (term) {
                            var requestData = {url: VODNew.Constant.thirdUrl_locationUrl, type: "get", params: {word: term, type: "province,city", domestic: 1}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"];
                                itemData["value"] = item["name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item["label"];
                        }
                    }
                }

                var videoSuggest = {
                    options: {
                        source: VODNew.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            return [];
                        },
                        validate: false,
                        getParam: function (term) {
                            var videotype = $('input[name=videotype]:checked').val();
                            $("input[name=videoName]").suggest("option", "stopSuggest", videotype == -1);
                            var requestData = {url: VODNew.Constant.thirdUrl_simple_video, type: "get", params: {word: term, type: "properTitle", isMade: videotype, filter_GTI_channel: 0 }, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["entityId"];
                                itemData[options.labelKey] = item["properTitle"];
                                itemData["value"] = item["properTitle"];

                                itemData["videoId"] = item["entityId"] || 0;
                                itemData["videoName"] = item["properTitle"] || "";

                                itemData["categoryName"] = item["categoryName"] || "";
                                itemData["categoryId"] = item["categoryId"] || 0;

                                itemData["albumName"] = item["albumDisplayName"] || "";
                                itemData["albumId"] = item["albumId"] || 0;
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        select: function (event, object) {
                            if (object.item.albumId > 0) {
                                $("input[name=albumName]").suggest("setValue", {id: object.item.albumId, label: object.item.albumName})
                            } else {
                                $("input[name=albumName]").suggest("setValue", "")
                            }
                            if (object.item.videoId > 0) {
                                $("input[name=videoName]").suggest("setValue", {id: object.item.videoId, label: object.item.videoName});
                                $("input[name=videoName]").attr("bind-sel-name", object.item.videoName);
                                $("input[name=videoName]").attr("bind-sel-id", object.item.videoId);
                            } else {
                                $("input[name=videoName]").suggest("setValue", "")
                            }
                            if (object.item.categoryId > 0) {
                                $("input[name=categoryName]").suggest("setValue", {id: object.item.categoryId, label: object.item.categoryName});
                                $("input[name=categoryName]").attr("bind-sel-name", object.item.categoryName);
                                $("input[name=categoryName]").attr("bind-sel-id", object.item.categoryId);
                            } else {
                                $("input[name=categoryName]").suggest("setValue", "")
                            }
                            $('input[name=albumName],input[name=categoryName]').attr('disabled', 'disabled');
                            return true;
                        },
                        template: function (item) {
                            return item["label"];
                        }
                    }
                }

                $("input[name=categoryName]").suggest(channelTypeSuggest.options);
                $("input[name=categoryName]").bind("blur", function (event) {
                    console.log("categoryName  blur ");
                    setTimeout(function () {
                        if ($("input[name=categoryName]").val() == "资讯" && $("input[name=categoryName]").suggest("getValue") == "25") {
                            $("#locationDiv").show();
                        } else {
                            $("#locationDiv").hide();
                        }
                    }, 100)
                })
                $("input[name=albumName]").suggest(albumSuggest.options);
                $("input[name=location]").suggest(locationSuggest.options);
                $("input[name=videoName]").suggest(videoSuggest.options);
                var paramsData = self.dao.getParamsData();
                if (parseInt(paramsData.locationCategory) > 0) {
                    $("input[name=location]").suggest("setValue", {id: paramsData.locationCategory, label: decodeURI(paramsData.location)})
                }
            },
            initGrid: function () {
                var self = this;
                self.initFrameGrid();
                self.initAdvertGrid();
                self.initNewsGrid();
                self.initNewsSubmitGrid();
                self.initNewsDelGrid();
                self.initMaskGrid();
                self.queryNews();
            },
            initFrameGrid: function (options, callback) {
                var self = this;
                self.config.PageBeanFrame = VODNew.Util.createPageBean();
                var gridConfig = self.getGridConfig(self.config.TABLE_FRAME_LIST);
                options = $.extend(true, {}, gridConfig, options);
                self.options.$FrameGrid.jqGrid(options);
            },
            initAdvertGrid: function (options, callback) {
                var self = this;
                self.config.PageBeanAdvert = VODNew.Util.createPageBean();
                var gridConfig = self.getGridConfig(self.config.TABLE_ADVERT_LIST);
                options = $.extend(true, {}, gridConfig, options);
                self.options.$AdvertGrid.jqGrid(options);
            },
            initNewsSubmitGrid: function (options, callback) {
                var self = this;
                self.config.PageBeanNewsSubmit = VODNew.Util.createPageBean();
                var gridConfig = self.getGridConfig(self.config.TABLE_MERGE_SUBMIT_LIST);
                options = $.extend(true, {}, gridConfig, options);
                self.options.$NewsSubmitGrid.jqGrid(options);
            },
            initNewsDelGrid: function (options, callback) {
                var self = this;
                self.config.PageBeanNewsDel = VODNew.Util.createPageBean();
                var gridConfig = self.getGridConfig(self.config.TABLE_MERGE_DEL_LIST);
                options = $.extend(true, {}, gridConfig, options);
                self.options.$NewsDelGrid.jqGrid(options);
            },
            initMaskGrid: function (options, callback) {
                var self = this;
                self.config.PageBeanMaskEntity = VODNew.Util.createPageBean();
                var gridConfig = self.getGridConfig(self.config.TABLE_MASK_LIST);
                options = $.extend(true, {}, gridConfig, options);
                self.options.$MaskGrid.jqGrid(options);
                var htmlArr = [];
                htmlArr.push("<button type='button' onclick='VODNew.MaskManager.addMaskEntity()'>添加</button>");
                htmlArr.push("<button type='button' onclick='VODNew.MaskManager.clearMaskEntity()'>清空</button>");
                $("#mask_pager_left").css({width: "10px"});
                $(htmlArr.join("")).appendTo($("#t_mask_list"));
            },

            initNewsGrid: function (options, callback) {
                var self = this;
                self.config.PageBeanNews = VODNew.Util.createPageBean();
                var gridConfig = self.getGridConfig(self.config.TABLE_NEWS_LIST2);
                options = $.extend(true, {}, gridConfig, options);
                self.options.$NewsGrid.jqGrid(options);
                $("#news_list").setGridHeight(100)
                $("#news_pager_left").css({width: "10px"});
                var htmlArr = [];
                htmlArr.push("<button type='button' name='refresh_tab2'>刷新</button>");
//                htmlArr.push("<button type='button' onclick='VODNew.Util.doQuickAdd()'>添加</button>");
                htmlArr.push("<button type='button' onclick='VODNew.Util.doQuickMerge()'>合并</button>");
                htmlArr.push("<button type='button' onclick='VODNew.Util.doSelectedAll(true)'>全选</button>");
                htmlArr.push("<button type='button' onclick='VODNew.Util.doSelectedAll(false)'>清除选中</button>");
                $(htmlArr.join("")).appendTo($("#t_news_list"));
                $("button[name=refresh_tab2]").click(function (event) {
                    if (VODNew.Util.hasImportData()) {
                        VODNew.Util.doClearImportData("all")
                    }
                    self.queryNews();
                })
            },

            queryNews: function () {
                var self = this;
                var taskid = VODNew.Dao.settings.taskid;
                if (taskid == 0) {
                    console.log("queryNews taskid = 0");
                    return;
                }
                $("#news_list").jqGrid("setGridParam", {selrow: null});
                VODNew.Util.clearHighLight();
                self.dao.getNewsList({key: taskid, from_client: true, index: 0, type: 1, offset: 100 }, function (data) {
                    if (data != null && data.list != null) {
                        var formatArr = [];
                        self.dao.settings.reg_last_id = 0;
                        var regId = self.dao.settings.reg_last_id;
                        $.each(data.list, function (i, element) {
                            regId++;
                            formatArr.push({ title: element.text, sTime: element.video_list[0], eTime: element.video_list[element.video_list.length - 1], pic: element.cover, id: element.id, regId: regId, checked: false })
                        })
                        self.dao.settings.reg_last_id = regId
                        var lastSortSource = self.config.PageBeanNewsDel.getSource();
                        if (lastSortSource.length > 0) {
                            formatArr = VODNew.Util.doSourceRemove(lastSortSource, formatArr);
                        }
                        self.config.PageBeanNews.setNewData(formatArr, 100);
                    } else {
                        self.config.PageBeanNews.setNewData([], 100);
                    }
                    if (self.config.PageBeanNews.getSource().length > 0) {
                        VODNew.Util.hasIntelligentData();
                    } else {
                        VODNew.Util.nonIntelligentData();
                    }
                    var retValue = self.config.PageBeanNews.getCur();
                    self.options.$NewsGrid.clearGridData();
                    self.options.$NewsGrid[0].addJSONData(retValue);
                });
            }
        })
    }
);
define(
    '../vodnew/VODNew.AccurateFrame',['require','exports','module'],function (require, exports, module) {
        VODNew.AccurateFrame = (function () {
           // var adAccurate = {};
            var openFlag = false;
            var openMode = null;
            var adAccurateFrame = {
                'head': '', //打点精确化起始帧
                'end': '', //打点精确化结束帧
                'endSetted': false,
                'headSetted': false
            }
            var params = ["fragment-l", "fragment-r", "ad-l", "ad-r",'p-r','p-l'];
            var accurateFrame = {
                'head': '', //打点精确化起始帧
                'end': '', //打点精确化结束帧
                'endSetted': false,
                'headSetted': false
            }
            //搭建js与flash互通的环境
            function thisMovie(movieName) {
                if (navigator.appName.indexOf("Microsoft") != -1) {
                    return window[movieName];
                } else {
                    return document[movieName];
                }
            }

            function doReset() {
                accurateFrame = {
                    'head': '', //打点精确化起始帧
                    'end': '', //打点精确化结束帧
                    'endSetted': false,
                    'headSetted': false
                }
            }

            function accurateStartEndRemove() {
                openFlag = false;
                var frameId = thisMovie('accurateStartEndFrame').get_select_index();

                if (frameId == -1) {
                    frameId = '';
                }
                var redParent = $('.red').parent();
                var picId = parseInt( $('.red').parent().find(".pid").text());
                if (redParent.find(".p-l").length > 0) {
                    accurateFrame.head = frameId;

                    if (accurateFrame.head){
                        accurateFrame.headSetted = true;
                        accurateFrame.headPic = picId
                    }

                }
                else if (redParent.find(".p-r").length > 0) {
                    accurateFrame.end = frameId;
                    if (accurateFrame.end){
                        accurateFrame.endSetted = true;
                        accurateFrame.endPic = picId;
                    }

                }
                else if (redParent.find(".ad-l").length > 0) {

                    adAccurateFrame.head = frameId;

                    if (adAccurateFrame.head){
                        adAccurateFrame.headSetted = true;
                        adAccurateFrame.headPic = picId
                    }
                }
                else if (redParent.find(".ad-r").length > 0) {
                    adAccurateFrame.end = frameId;
                    if (adAccurateFrame.end){
                        adAccurateFrame.endSetted = true;
                        adAccurateFrame.endPic = picId;
                    }
                }

                $('#accurateStartEndOutDiv').css({
                    'left': '-10000px',
                    'top': '-10000px'
                });
            }

            // 打点精确化数据加载
            function accurateStartEndPlay(imgSrc) {
                var analysis = VODNew.Dao.getDotData().analysis;
                $('#accurateStartEndOutDiv').css({
                    'left': '0px',
                    'top': '0px'
                });
                thisMovie('accurateStartEndFrame').change_flv_url(analysis + "?file=" + imgSrc + "&from_client=true");
                openFlag = true;
            }

            function getAccurateFrame() {
                return accurateFrame;
            }

            function updateAccurateFrame(options) {
                VODNew.Util.updateObjectData(options, accurateFrame)
            }

            function getAdAccurate() {
                return adAccurateFrame;
            }

            // has marked ad will be removed
            function adTipRemove() {
                $('.ad-l').remove();
                $('.ad-r').remove();
                adAccurateFrame = {
                    'head': '', //打点精确化起始帧
                    'end': '', //打点精确化结束帧
                    'endSetted': false,
                    'headSetted': false
                }
            }

            // has marked fragment will be removed
            function fgTipRemove() {
                $('.fragment-l').remove();
                $('.fragment-r').remove();
            }

            function handler_keyCodeQ() {
                openMode = "accurateFrame"
                var selected = $(".red").parent();
                $.each(params, function (i, element) {
                    if(selected.find("."+element).length > 0){
                        accurateStartEndPlay(selected.find("img").attr("src"));
                    }
                })
            }

            function doLastHandlerQ(){
                if( openMode == "accurateFrame"){
                    handler_keyCodeQ();
                }
            }

            function readFrameData(frameData){
                accurateFrame = $.extend(true,{},frameData);
            }
            function isDlgOpen(){
                return  openFlag;
            }

            return {
                accurateStartEndPlay: accurateStartEndPlay,
                accurateStartEndRemove: accurateStartEndRemove,
                getAccurateFrame: getAccurateFrame,
                updateAccurateFrame: updateAccurateFrame,
                getAdAccurate: getAdAccurate,
                adTipRemove: adTipRemove,
                fgTipRemove: fgTipRemove,
                handler_keyCodeQ: handler_keyCodeQ,
                doReset: doReset,
                readFrameData:readFrameData,
                isDlgOpen:isDlgOpen,
                doLastHandlerQ:doLastHandlerQ
            }
        })()
    }
);
define(
    '../vodnew/VODNew.Advert',['require','exports','module'],function (require, exports, module) {
        VODNew.Advert = (function () {
            function getSubmitAdData() {
                var advertAccurateData = VODNew.AccurateFrame.getAdAccurate();
                var d_sTime = $('input[name=d_sTime]').val();
                var d_eTime = $('input[name=d_eTime]').val();
                var d_title = $('input[name=d_videoName]').val();
                return {
                    'index': VODNew.Dao.settings.index,
                    'sTime': d_sTime,
                    'eTime': d_eTime,
                    'title': d_title,
                    'channel': '',
                    'album': '',
                    'pic': '',
                    'head': advertAccurateData.head,
                    'end': advertAccurateData.end,
                    'headSetted': advertAccurateData.headSetted,
                    'endSetted': advertAccurateData.endSetted,
                    'headPic': advertAccurateData.headPic,
                    'endPic': advertAccurateData.endPic
                }
            }

            function addAdvertProgress(progressObj, skipCheck) {
                skipCheck = skipCheck == null ? false : skipCheck == true
                progressObj.doBefore();
                if (progressObj.doCheck(skipCheck)) {
                    progressObj.doSubmit(progressObj.doFinal, progressObj.doCallBack);
                } else {
                    progressObj.doFinal();
                }
            }

            function del_submit(forceFlag) {
                var dataSubmit = getSubmitAdData();
                var data = {
                    '起始帧': dataSubmit.sTime,
                    '结束帧': dataSubmit.eTime,
                    '标题': dataSubmit.title
                };
                var needRemind = VODNew.Util.checkAdvertAffectDot(dataSubmit.sTime, dataSubmit.eTime);
                var progressObj = {
                    doBefore: function () {
                        $('#d_addInfo').attr('disabled', 'disabled');
                    },
                    doCheck: function (skipCheck) {
                        if (skipCheck) {
                            return true;
                        }
                        if (!VODNew.Util.checkStAndEt(dataSubmit.sTime, dataSubmit.eTime)) {
                            console.log("interrupt checkLiveType checkRepeat")
                            return false;
                        }
                        if (!VODNew.Util.validAddInfo(data)) {
                            return false;
                        }
                        if(!checkAdvertCross(dataSubmit)){
                            VODNew.Plugin.tips("error", VODNew.Config.REMIND_MSG_INFO.ADVERT_CROSS);
                            return false;
                        }
                        if (needRemind) {
                            SystemDialog.queryConfirm(VODNew.Config.REMIND_MSG_INFO.ADVERT_SUBMIT, function (flag) {
                                if (flag == true) {
                                    VODNew.Advert.del_submit(true);
                                }
                            }, {"btn_ok": "确认提交广告"})
                            return false;
                        }
                        return true;
                    },
                    doSubmit: function (revertHandler, callback) {
                        VODNew.Config.Global.d_sty2Data.push(dataSubmit);
                        var tempHandler = function () {
                            $('input[name=d_sTime]').val('');
                            $('input[name=d_eTime]').val('');
                            VODNew.Dao.settings.index++;
                            VODNew.AccurateFrame.adTipRemove(); // 广告左右标识删除
                            VODNew.Plugin.tips("success", '删除成功');
                            if (callback != null) {
                                callback();
                            }
                        }
                        advertAddInfo(dataSubmit, tempHandler, revertHandler)
                    },
                    doFinal: function () {
                        $('#d_addInfo').removeAttr('disabled').html('提交');
                    }
                }
                if (needRemind) {
                    progressObj.doCallBack = function () {
                        VODNew.Util.doQuickFragmentSubmit();
                    }
                }
                addAdvertProgress(progressObj, forceFlag);
            }

            function checkAdvertCross(data){
                data.sTime = parseInt(data.sTime);
                data.eTime = parseInt(data.eTime);

                var advertSource = VODNew.Config.PageBeanAdvert.getSource();
                var temp = [];
                $.each(advertSource, function (i, element) {
                    for (var i = element.sTime; i <= element.eTime; i++) {
                        temp.push(i);
                    }
                })
                var uniqueArr = temp;

                temp = [];
                for (var i = data.sTime; i <= data.eTime; i++) {
                    temp.push(i);
                }
                var totalLength = uniqueArr.length + temp.length;
                $.each(temp, function (i, el) { //去重复
                    if ($.inArray(el, uniqueArr) === -1)
                        uniqueArr.push(el);
                });
                if (uniqueArr.length < totalLength) {
                    return false;
                }
                return true
            }

            function advertAddInfo(data, tempHandler, revertHandler) {
                $('#d_addInfo').html('成功');
                data.sTime = parseInt(data.sTime);
                data.eTime = parseInt(data.eTime);
                var tempList = [];
                if (VODNew.Config.ADVERT_SUPPORT) {
                    if (data.headSetted) {
                        tempList.push({id: data.headPic, type: 0, offset: data.head})
                    }
                    if (data.endSetted) {
                        tempList.push({id: data.endPic, type: -1, offset: data.end })
                    }
                }
                var sendData = null;
                if (tempList.length > 0) {
                    sendData = {key: VODNew.Dao.settings.taskid, list: JSON.stringify(tempList), from_client: true};
                }
                VODNew.Dao.doAdvertCutAdd(sendData, function (rdata) {
                    revertHandler();
                    var suc = rdata != null && rdata.code == VODNew.Config.CODE_SUC
                    if (suc) {
                        VODNew.Config.PageBeanAdvert.addNewOne(data);
                        VODNew.Util.updateGridAdvert();
                        accountDelList();
                        tempHandler();
                        if (sendData != null) {
                            VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.addAdvertAccurate, sendData, rdata, VODNew.Dao.getDotData().doadadd);
                        }
                    } else {
                        if (sendData != null) {
                            VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.addAdvertAccurate, sendData, {error: "提交广告精确化失败!"}, VODNew.Dao.getDotData().doadadd);
                        }
                    }
                })
            }

            function advertRemoveInfo(findData, tempHandler) {
                var tempList = [];
                if (VODNew.Config.ADVERT_SUPPORT) {
                    if (findData.headSetted) {
                        tempList.push(findData.headPic);
                    }
                    if (findData.endSetted) {
                        tempList.push(findData.endPic);
                    }
                }
                var sendData = null;
                if (tempList.length > 0) {
                    sendData = {key: VODNew.Dao.settings.taskid, list: JSON.stringify(tempList), from_client: true};
                }
                VODNew.Dao.doAdvertCutDel(sendData, function (rdata) {
                    var suc = rdata != null && rdata.code == VODNew.Config.CODE_SUC
                    if (suc) {
                        VODNew.Config.PageBeanAdvert.delOne(findData)
                        VODNew.Util.updateGridAdvert();
                        accountDelList();
                        tempHandler();
                        if (sendData != null) {
                            VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.delAdvertAccurate, sendData, rdata, VODNew.Dao.getDotData().doaddel);
                        }
                    } else {
                        if (sendData != null) {
                            VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.delAdvertAccurate, sendData, {error: "删除广告精确化失败!"}, VODNew.Dao.getDotData().doaddel);
                        }
                    }
                })
            }

            function delAdvert(rowId) {
                var findData = VODNew.Config.PageBeanAdvert.findData("index", rowId);
                if (findData != null) {
                    var needCheck = VODNew.Util.checkAdvertAffectDot(findData.sTime, findData.eTime);
                    var progressObj = {
                        doBefore: function () {
                        },
                        doCheck: function (skipCheck) {
                            return true;
                        },
                        doSubmit: function (revertHandler, callback) {
                            SystemDialog.queryConfirm(needCheck ? VODNew.Config.REMIND_MSG_INFO.ADVERT_DEL : VODNew.Config.REMIND_MSG_INFO.NORMAL, function (flag) {
                                if (flag === true) {
                                    var tempHandler = function () {
                                        if (callback != null) {
                                            callback();
                                        }
                                    }
                                    advertRemoveInfo(findData, tempHandler)
                                }
                            }, {"btn_ok": "确认删除广告"})
                        },
                        doFinal: function () {
                        }
                    }
                    if (needCheck) {
                        progressObj.doCallBack = function () {
                            VODNew.Util.doQuickFragmentSubmit();
                        }
                    }
                    addAdvertProgress(progressObj, false)
                }
            }

            function accountDelList() {
                var arr3 = [];
                var settings = VODNew.Dao.settings;
                var advertSource = VODNew.Config.PageBeanAdvert.getSource();
                $.each(advertSource, function (i, element) {
                    if(element.headSetted != true){
                        arr3.push(element.sTime);
                    }
                    for (var i = element.sTime + 1; i < element.eTime; i++) {
                        arr3.push(i);
                    }
                    if(element.endSetted != true){
                        arr3.push(element.eTime);
                    }
                })
                var uniqueArr3 = [];
                $.each(arr3, function (i, el) { //去重复
                    if ($.inArray(el, uniqueArr3) === -1)
                        uniqueArr3.push(el);
                });
                settings.delList = uniqueArr3;
            }

            return {
                del_submit: del_submit,
                delAdvert: delAdvert
            }
        })()
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../vodnew/VODNew.Task',['require','exports','module'],function (require, exports, module) {
        VODNew.Task = (function () {
            var settings = VODNew.Dao.settings;
            var dotData = VODNew.Dao.getDotData();
            var global = VODNew.Config.Global;
            var getData = function () {
                $('#addInfo,#d_addInfo').removeAttr('disabled').html('提交');

                if (settings.isOver == 0) {
                    return false;
                }
                var listUrl = dotData.listUrl;
                if (settings.taskid > 0 && settings.isStart) {
                    settings.isOver = 0
                    $.ajax({
                        type: "get",
                        url: listUrl,
                        data: {
                            'key': settings.taskid,
                            'from_client': true,
                            'index': settings.lastImg,
                            'type': 1,
                            'offset': 100
                        },
                        success: function (data) {
                            settings.isOver = 1 //防止并发
                            if (data.list.length) {
                                var li = '';
                                var sty = global.picWH;
                                var thisFpTime = "";
                                $.each(data.list, function (i, value) {
                                    var fp_time = value.fp;
                                    global.fp_pos = fp_time.lastIndexOf('/') + 1;
                                    fp_time = fp_time.substr(global.fp_pos, 10);
                                    if (!settings.isSetFpTime) {
                                        settings.firstFpTime = parseInt(fp_time);
                                        thisFpTime = '00:00:00';
                                    } else {
                                        var tmpFpTime = (parseInt(fp_time) - settings.firstFpTime);
                                        thisFpTime = VODNew.Util.getDataByNum(tmpFpTime);
                                    }
                                    //////////////////////////////////////////////////////////////////////////////////////////

                                    var s = [];
                                    s.push('<div class="text-center relative ' + thisFpTime.replace(/:/g, "-") + ' ' + value.id + '-jump" id="cate-' + value.vid + '">');
                                    s.push('<img class="fragment-img" id="img-' + value.id + '"  duration="'+value.length+'"   src="' + value.fp + '"  ondblclick="VODNew.Util.dl_img_click(event, \'' + value.id + '\');" onerror="VODCom.Player.nofind(\'' + value.fp + '\');"' + sty + ' />');
                                    s.push('<div class="absolute ' + settings.fpTime + '">' + thisFpTime + '</div><br/>')
                                    s.push('<span class="pid">' + value.id + '</span>')
                                    s.push('</div>')
                                    //////////////////////////////////////////////////////////////////////////////////
                                    $('#makedImg').append(s.join(""));
                                    //出来第一张图的时候计算几张图片一行
                                    if (!settings.isSetFpTime) {
                                        VODNew.Util.getLineWidth();
                                        settings.isSetFpTime = true;
                                    }
                                    li = value.id + 1;
                                    settings.lb++;
                                });

                                if(data.list.length > 0 ){
                                    VODCom.NewsHighlight.triggerAddNewImage();
                                }
                                if (li) {
                                    settings.lastImg = li;
                                    $('#picNum').html(li);
                                }
                                if ($('#autoRunPic').prop('checked')) {
                                    var sTop = $('#makedImg')[0].scrollHeight;
                                    $('#makedImg').scrollTop(sTop);
                                }

                            } else {
                                //请求无数据的次数
                                if (settings.noneDataNum > 5) {
                                    console.log('请求错误超过5次');
                                } else {
                                    settings.noneDataNum++
                                }
                            }
                        },
                        dataType: 'json',
                        error: function () {
                            settings.isOver = 1;
                            //alert('图片请求错误,再次尝试请求中!');
                            VODNew.Plugin.tips("error", '图片请求错误,再次尝试请求中!');
                        }
                    });
                } else {
                    console.log("null taskid")
                }
            }
            return {
                getData: getData
            }
        })()
    }
);
define(
    '../vodnew/VODNew.MaskManager',['require','exports','module'],function (require, exports, module) {
        VODNew.MaskManager = (function () {
            var _initOver = false;
            var _options = {};
            var Sys = {};

            Sys.Data = {
                index: 0,
                entityIdIndex: 1
            };
            Sys.Config = {
                CropInstance: null,
                isStart: false,
                selectMode: false,
                bindDiv: null,
                gridTarget: null,
                curImageId: -1
            };

            Sys.Util = {
                doCropRelease: function () {
                    console.log("doCropRelease ");
                    Sys.Util.clearBindDiv();
                    $(".maskSelected").removeClass("maskSelected");
                    if ($(".maskSelected").length > 0) {
                        var maskChild = $($(".maskSelected")[0]);
                        if (maskChild.width() < 25 || maskChild.height() < 25) {
                            maskChild.remove();
                        }
                    }
                },
                doCropSelect: function (obj) {
                    //   var showObj = {x: obj.x, y: obj.y, w: obj.w, h: obj.h};
                    var showRect = Sys.Config.CropInstance.tellScaled();
                    var actualRect = Sys.Config.CropInstance.tellSelect();
                    console.log("doCropSelect ", JSON.stringify(showRect), JSON.stringify(actualRect));
                    if (Sys.Config.selectMode) {
                        return;
                    }
                    var maskChild = null;
                    if ($(".maskSelected").length > 0) {
                        maskChild = $($(".maskSelected")[0]);
                        maskChild.css({width: showRect.w, height: showRect.h, "left": showRect.x, "top": showRect.y});
                        maskChild.data("actualRect", $.extend({}, actualRect));
                        maskChild.data("showRect", $.extend({}, showRect));
                        return;
                    } else {
                        maskChild = Sys.Config.bindDiv;
                    }

                    if (maskChild == null) {
                        Sys.Data.index++;
                        var maskChild = Sys.Util.createMaskChild(Sys.Data.index);
                        maskChild.appendTo(_options.maskDivTarget);
                    } else {
                        Sys.Util.clearBindDiv();
                    }
                    Sys.Config.CropInstance.release();
                    maskChild.css({width: showRect.w, height: showRect.h, "left": showRect.x, "top": showRect.y});
                    maskChild.data("actualRect", $.extend({}, actualRect));
                    maskChild.data("showRect", $.extend({}, showRect));
                },
                createMaskChild: function (index) {
                    var maskChild = $('<div><span onclick="VODNew.MaskManager.delegateDelResource(event)" data-id="' + index + '">X</span></div>');
                    maskChild.addClass("maskChild");
                    maskChild.attr("id", "maskChild_" + index);
                    return maskChild;
                },
                clearBindDiv: function () {
                    if (Sys.Config.bindDiv != null) {
                        Sys.Config.bindDiv.show();
                        Sys.Config.bindDiv = null;
                        console.log("Sys.Config.bindDiv clear ");
                    }
                },
                delResource: function (event) {
                    console.log("delResource ", event.target);
                    event.stopPropagation();
                    console.log("delResource end");
                    $(event.target).parent().remove();
                    Sys.Config.CropInstance.release();
                }
            };

            function initManager(options) {
                if (_initOver) {
                    console.log("has init over")
                    return;
                }
                _options = options;
                _options.btn_ok.on("click", function (e) {
                    recordMaskObjPos()
                    _options.dlgTarget.dialog("close");
                })
                _options.btn_cancel.on("click", function (e) {
                    _options.dlgTarget.dialog("close");
                });
                _options.btn_preview.on("click", function (e) {
                    doMaskPreview();
                });

                Sys.Config.CropInstance = $.Jcrop("#" + _options.imageTarget.attr("id"), {
                    onRelease: Sys.Util.doCropRelease,
                    onSelect: Sys.Util.doCropSelect,
                    boxHeight: 603,
                    minSelect: [25, 25]
                })

                _options.maskDivTarget.on("click", "div.maskChild", function (event) {
                    console.log("div.maskChild");
                    if (event.target != event.currentTarget) {
                        return false;
                    }
                    Sys.Util.clearBindDiv();
                    var maskChild = $(event.target);
                    var recordRect = maskChild.data("actualRect");
                    var newRect = [ recordRect.x, recordRect.y , recordRect.w, recordRect.h];
                    Sys.Config.selectMode = true;
                    Sys.Config.CropInstance.setSelect([newRect[0], newRect[1], newRect[0] + newRect[2], newRect[1] + newRect[3]  ]);
                    Sys.Config.selectMode = false;
                    Sys.Config.bindDiv = maskChild;
                    Sys.Config.bindDiv.hide();
                    return false
                })
            }

            function delegateDelResource(event) {
                Sys.Util.delResource(event);
            }

            function getPageBean() {
                return  VODNew.Config.PageBeanMaskEntity
            }

            function updateGrid() {
                VODNew.Util.updateGridMaskEntity()
            }

            function addMaskEntity() {
                var entity = createEntity();
                getPageBean().addNewOne(entity);
                updateGrid();
                $("#mask_list").jqGrid('setSelection', entity.index);
                VODNew.Util.setMaskHighLight(null);
            }

            function clearMaskEntity() {
                getPageBean().setNewData([]);
                updateGrid();
                VODCom.NewsHighlight.clearMaskMark();
            }

            function readMaskEntity() {
                var selRow = _options.gridTarget.jqGrid("getGridParam", "selrow");
                var findData = getPageBean().findData("index", selRow);
                if (findData.coverArr.length > 0) {
                    var maskChild = null;
                    $.each(findData.coverArr, function (i, element) {
                        maskChild = Sys.Util.createMaskChild(element.index);
                        maskChild.appendTo(_options.maskDivTarget);
                        maskChild.css({width: element.showRect.w, height: element.showRect.h, "left": element.showRect.x, "top": element.showRect.y});
                        maskChild.data("actualRect", $.extend({}, element.actualRect));
                        maskChild.data("showRect", $.extend({}, element.showRect));
                    })
                }
            }

            function createEntity() {
                var newId = Sys.Data.entityIdIndex;
                Sys.Data.entityIdIndex++;
                return  {
                    index: newId,
                    sTime: -1,
                    eTime: -1,
                    coverArr: []
                }
            }

            function delMaskEntity(rowId) {
                var findData = getPageBean().findData("index", rowId);
                if (findData != null) {
                    getPageBean().delOne(findData);
                    VODCom.NewsHighlight.clearMaskSingleMark(findData.index)
                    updateGrid();
                }
            }

            function modifyMaskEntity(index) {
                var selRow = _options.gridTarget.jqGrid("getGridParam", "selrow");
                console.log("selRow" + selRow);
                if (selRow == null) {
                    return;
                }
                var maskEntity = null;
                if (index != null) {
                    var maskEntity = getPageBean().findData("index", index);
                    if (maskEntity != null && maskEntity.sTime >= 0) {
                        VODNew.Util.doMaskImage(maskEntity.sTime);
                    }
                } else {
                    maskEntity = getPageBean().findData("index", parseInt(selRow));
                    var imageId = parseInt($(".red").parent().find(".pid").html());
                    if (maskEntity.sTime >= 0 && maskEntity.sTime <= imageId) {
                        VODNew.Util.doMaskImage(imageId)
                    }
                }
            }

            function getSelectMaskEntity() {
                var selRow = _options.gridTarget.jqGrid("getGridParam", "selrow");
                if (selRow == null) {
                    return null;
                }
                return  getPageBean().findData("index", parseInt(selRow));
            }

            function doMaskPreview() {
                if (Sys.Config.curImageId == -1) {
                    console.log(" doMaskPreview fail")
                    return;
                }
                var coverArr = makeUpCoverArr();
                var subArr = [];
                $.each(coverArr, function (i, element) {
                    subArr.push(
                        {
                            x: parseInt(element.actualRect.x),
                            y: parseInt(element.actualRect.y),
                            w: Math.ceil(element.actualRect.w),
                            h: Math.ceil(element.actualRect.h)
                        }
                    )
                })
                var sendData = {
                    //  image_id: Sys.Config.curImageId,
                    //     channel_code: paramsData.channel_name,
                    from_client: true,
                    key: VODNew.Dao.settings.taskid,
                    delogo: JSON.stringify(subArr)
                };
                $("#navMaskDiv").tabs({active: 1})
//                $("#demoImg").attr("src", "img/demo_test.jpg")
                VODNew.Dao.getMaskResult(sendData, function (rdata) {
                    if (rdata != null && rdata.code == "A00000") {
                        $("#demoImg").attr("src", rdata.uri + "?t=" + Math.random());
                        console.log("getMaskResult suc" + JSON.stringify(rdata));
                    } else {
                        console.log("getMaskResult fail")
                    }
                })
            }

            function recordMaskObjPos() {
                var maskEntity = getSelectMaskEntity();
                maskEntity.coverArr = makeUpCoverArr();
            }

            function makeUpCoverArr() {
                var retVal = [];
                var childArr = _options.maskDivTarget.children();
                $.each(childArr, function (i, element) {
                    retVal.push({
                            actualRect: $(element).data("actualRect"),
                            showRect: $(element).data("showRect"),
                            index: parseInt($(element).attr("id").replace("maskChild_", ""))
                        }
                    )
                })
                return retVal;
            }

            function makeUpSubDelogoArr() {
                var source = getPageBean().getSource();
//maskJson: [{st,et,coverArr:[{x,y,w,h}]},]
                var subArr = [];
                var singleData = null;
                $.each(source, function (i, single) {
                    singleData = { st: single.sTime, et: single.eTime, coverArr: []};
                    $.each(single.coverArr, function (i, element) {
                        singleData.coverArr.push(
                            {
                                x: parseInt(element.actualRect.x),
                                y: parseInt(element.actualRect.y),
                                w: Math.ceil(element.actualRect.w),
                                h: Math.ceil(element.actualRect.h)
                            }
                        )
                    })
                    subArr.push(singleData);
                })
                return subArr
            }

            function isValidDelogo(source) {
                var isValid = true;
                $.each(source, function (i, single) {
                    if (single.sTime > single.eTime || single.eTime < 0 || single.sTime < 0) {
                        isValid = false;
                        return false
                    }
                })
                return isValid;
            }

            function startWork(showImageId) {
                _options.dlgTarget.dialog("open");
                _options.maskDivTarget.html("");
                $("#navMaskDiv").tabs({active: 0});
                $("#demoImgDiv").css({width: 900, height: 600});
                $("#demoImg").attr("src", "");
                var imageId = showImageId;
                if (imageId == null) {
                    return;
                }
                var paramsData = VODNew.Dao.getParamsData();
                var data = {
                    image_id: imageId,
                    channel_code: paramsData.channel_name,
                    from_client: true,
                    key: VODNew.Dao.settings.taskid
                };
                VODNew.Dao.getOcrImage(data, function (rdata) {//
                    if (rdata != null && rdata.code == "A00000") {
                        var tempHandler = function (rdata2) {
                            Sys.Config.curImageId = -1;
                            if (rdata2 != null && rdata2.code == "A00000") {
                                Sys.Config.curImageId = imageId;
                                Sys.Config.CropInstance.setImage(rdata2.uri);
                                _options.maskDivTarget.html("");
                                readMaskEntity();
                                console.log("startWork doMaskImage suc")
                            } else {
                                VODNew.Plugin.tips("error", VODNew.Config.REMIND_MSG_INFO.GET_IMG_FAIL);
                                VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.getImageData, data, {error: VODNew.Config.REMIND_MSG_INFO.GET_IMG_FAIL}, VODNew.Dao.getDotData().findImage);
                                VODNew.Util.notifyAlert(VODNew.Config.REMIND_MSG_INFO.GET_IMG_FAIL + ";" + VODNew.Dao.getDotData().ocrimage + "|" + JSON.stringify(data).replace(/"/g, ""));
                            }
                        }
                        if (VODNew.Config.READ_IMAGE_METHOD == "new") {
                            VODNew.Dao.doFindImage("mask_image", data, tempHandler)
                        } else {
                            tempHandler(rdata);
                        }
                    } else {
                        VODNew.Plugin.tips("error", "请求图片失败!");
                    }
                });
            }
            //  function remove
            return {
                initManager: initManager,
                addMaskEntity: addMaskEntity,
                clearMaskEntity: clearMaskEntity,
                delMaskEntity: delMaskEntity,
                modifyMaskEntity: modifyMaskEntity,
                getSelectMaskEntity: getSelectMaskEntity,
                startWork: startWork,
                recordMaskObjPos: recordMaskObjPos,
                isValidDelogo: isValidDelogo,
                makeUpSubDelogoArr: makeUpSubDelogoArr,
                delegateDelResource: delegateDelResource
            }
        })()
    }
);
define(
    '../vodnew/VODNew.MarkOcrManager',['require','exports','module'],function (require, exports, module) {
        VODNew.MarkOcrManager ={
            doMarkOcrImage: function () {
                $("#image_mark-dlg").dialog("open");
                VODNew.MarkOcrManager.doMarkOcrImageReset();
                var imageId = parseInt($(".red").parent().find(".pid").html());
                var paramsData = VODNew.Dao.getParamsData();
                var data = {
                    image_id: imageId,
                    channel_code: paramsData.channel_name,
                    from_client: true,
                    key: VODNew.Dao.settings.taskid
                };
                //_channel_id
                VODNew.Dao.getOcrImage(data, function (rdata) {
                    if (rdata != null && rdata.code == "A00000") {
                        VODNew.Dao.doFindImage("ocr_image", data, function (rdata2) {
                            if (rdata2 != null && rdata2.code == "A00000") {
                                $("#ocr_image_div").show();
                                $("#ocr_image").attr("src", rdata2.uri);
                                VODNew.Config.CropInstance.setImage(rdata2.uri);
                                console.log("  doMarkOcrImage suc")
                            } else {
                                $("input[name=image_location]").val(rdata2 == null ? "无数据" : rdata2.msg);
                                VODNew.Plugin.tips("error", VODNew.Config.REMIND_MSG_INFO.GET_IMG_FAIL);
                                VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.getImageData, data, {error: VODNew.Config.REMIND_MSG_INFO.GET_IMG_FAIL}, VODNew.Dao.getDotData().findImage);
                                VODNew.Util.notifyAlert(VODNew.Config.REMIND_MSG_INFO.GET_IMG_FAIL + ";" + VODNew.Dao.getDotData().ocrimage + "|" + JSON.stringify(data).replace(/"/g, ""));
                            }
                        })
                    } else {
                        VODNew.Plugin.tips("error", "请求图片失败!");
                    }
                })
            },
            doMarkOcrImageReset: function () {
                $("#ocr_image_div").hide();
                $("input[name=image_ocr_title]").val("");
                $("input[name=origin_ocr_title]").val("");
                $("input[name=image_ocr_title]").change();
                $("input[name=image_location]").val("");
                VODNew.Config.OCR_RESULT_CALL = false;
            },
            fillByOcrTitle: function () {
                if (VODNew.Config.OCR_RESULT_CALL) {
                    VODNew.Config.OCR_TITLE_FLAG = 1;
                    VODCom.AutoTitle.AUTO_TITLE_FLAG = 0;
                    // 关联用户选定的
                    VODCom.AutoTitle.USER_TITLE_SELECT = parseInt($(".red").parent().find(".pid").html())
                }
                VODNew.Config.OCR_TITLE_ORIGIN = $("input[name=origin_ocr_title]").val();
                var title = $("input[name=image_ocr_title]").val();
                if (title.trim().length > 0) {
                    $("input[name=videoName]").val(title.trim());
                    $("input[name=videoName]").change();
                }
            },
            doCropChange: function (obj) {

            },
            doCropSelect: function (obj) {
                console.log("doCropSelect " + JSON.stringify(obj));
                var scale = 1;
                var showObj = {
                    x: parseInt(obj.x / scale),
                    y: parseInt(obj.y / scale),
                    w: Math.ceil(obj.w / scale),
                    h: Math.ceil(obj.h / scale)
                };
                console.log("doCropSelect " + JSON.stringify(obj) + "," + JSON.stringify(showObj))
                $("input[name=image_location]").val(JSON.stringify(showObj));
                VODNew.MarkOcrManager.reqOcrResult(showObj);
            },
            reqOcrResult: function (obj) {
                var imageId = parseInt($(".red").parent().find(".pid").html());
                var paramsData = VODNew.Dao.getParamsData();
                var data = {
                    image_id: imageId,
                    channel_code: paramsData.channel_name,
                    from_client: true,
                    key: VODNew.Dao.settings.taskid,
                    x: obj.x,
                    y: obj.y,
                    w: obj.w,
                    h: obj.h
                };
                VODNew.Dao.getOcrResult(data, function (rData) {
                    console.log("getOcrResult:" + rData == null ? "" : JSON.stringify(rData));
                    if (rData != null && rData.code == "A00000") {
                        rData.result = rData.result.trim();
                        $("input[name=image_ocr_title]").val(rData.result);
                        $("input[name=origin_ocr_title]").val(rData.result);
                        VODNew.Config.OCR_RESULT_CALL = true;
                    } else {
                        $("input[name=image_ocr_title]").val("");
                        $("input[name=origin_ocr_title]").val("");
                        VODNew.Plugin.tips("error", "识别标题失败!");
                        VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.submitOcrTitleData, data, {error: "识别标题失败!"}, $("#ocr_image").attr("src"));
                        VODNew.Util.notifyAlert("ocr识别标题失败:" + $("#ocr_image").attr("src") + "|" + JSON.stringify(data).replace(/"/g, ""));
                    }
                    $("input[name=image_ocr_title]").change();
                })
            }
        }
    }
);
/**
 * Copyright 2015 Qiyi.com All rights reserved.
 *
 * file: epg.js
 * path: js-src/
 * description: epg业务合并文件，通过该文件引入业务功能模块的js文件
 *              配置文件将用来生成合并文件
 * author: jiegang@qiyi.com
 * date: 2015-1-6
 */
define(
    'vodnew', [
        "../ancestor/Ancestor",
        "../ancestor/Ancestor.Dao",
        "../ancestor/Ancestor.Grid",
        "../ancestor/Ancestor.Config",
        "../ancestor/Ancestor.Util",
        "../ancestor/Ancestor.Dao",
        "../epg2/EpgWeb",
        "../epg2/EpgWeb.Util",
        "../epg2/EpgWeb.Plugin",
        "../epg2/EpgWeb.Dao",
        "../epg2/EpgWeb.Task",
        "../epg2/EpgWeb.PingBack",
        "../epg2/EpgWeb.PingBackCost",
        "../vodcom/VODCom",
        "../vodcom/VODCom.EventManager",
        "../vodcom/VODCom.Pic",
        "../vodcom/VODCom.OCR",
        "../vodcom/VODCom.TitleFilter",
        "../vodcom/VODCom.FlashToJS",
        "../vodcom/VODCom.H5PlayerControl",
        "../vodcom/VODCom.H5Player",
        "../vodcom/VODCom.AutoTitle",
        "../vodcom/VODCom.Player",
        "../vodcom/VODCom.NewsHighlight",
        "../vodnew/VODNew",
        "../vodnew/VODNew.Action",
        "../vodnew/VODNew.Config",
        "../vodnew/VODNew.Util",
        "../vodnew/VODNew.Plugin",
        "../vodnew/VODNew.Evt",
        "../vodnew/VODNew.Dao",
        "../vodnew/VODNew.EditMerge",
        "../vodnew/VODNew.AccurateFrame",
        "../vodnew/VODNew.Advert",
        "../vodnew/VODNew.Task",
        "../vodnew/VODNew.MaskManager",
        "../vodnew/VODNew.MarkOcrManager"
    ],

    function() {
        console.log('vodnew load done:', 'vodnew');
        if (SystemDialog && SystemDialog.initSystemDialog) {
            SystemDialog.initSystemDialog();
        }
    }
);

